#include <cstdio> #include <queue> #include <vector> #include <cstring> #include <climits> using namespace std; const int MAXN = 200000; int p[MAXN+5]; int dist[MAXN+5]; int s[MAXN+5]; vector<vector<int>> edges; int main() { int n; scanf("%d", &n); edges.reserve(n); for(int i = 0; i < n; ++i) { scanf("%d", &p[i]); --p[i]; } for (int i = 0; i < n; ++i) { for (int j = i+1; j < n; ++j) { if (p[j] < p[i]) { edges[i].push_back(j); edges[j].push_back(i); } } } for (int i = 0; i < n; ++i) { for (int j=0; j < n; ++j) { if (j == i) dist[j] = 0; else dist[j] = INT_MAX; } queue<int> q; auto &le = edges[i]; for (auto it = le.begin(); it != le.end(); ++it) { dist[*it] = 1; q.push(*it); } while(!q.empty()) { int j = q.front(); int dc = dist[j]+1; q.pop(); auto &lle = edges[j]; for (auto it = lle.begin(); it != lle.end(); ++it) { if (dist[*it] == INT_MAX) { q.push(*it); } dist[*it] = min(dist[*it], dc); } } for (int j = 0; j < n; ++j) { if (dist[j] < INT_MAX) { s[i] += dist[j]; } } } for (int i = 0; i < n; ++i) { printf("%d ", s[i]); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #include <cstdio> #include <queue> #include <vector> #include <cstring> #include <climits> using namespace std; const int MAXN = 200000; int p[MAXN+5]; int dist[MAXN+5]; int s[MAXN+5]; vector<vector<int>> edges; int main() { int n; scanf("%d", &n); edges.reserve(n); for(int i = 0; i < n; ++i) { scanf("%d", &p[i]); --p[i]; } for (int i = 0; i < n; ++i) { for (int j = i+1; j < n; ++j) { if (p[j] < p[i]) { edges[i].push_back(j); edges[j].push_back(i); } } } for (int i = 0; i < n; ++i) { for (int j=0; j < n; ++j) { if (j == i) dist[j] = 0; else dist[j] = INT_MAX; } queue<int> q; auto &le = edges[i]; for (auto it = le.begin(); it != le.end(); ++it) { dist[*it] = 1; q.push(*it); } while(!q.empty()) { int j = q.front(); int dc = dist[j]+1; q.pop(); auto &lle = edges[j]; for (auto it = lle.begin(); it != lle.end(); ++it) { if (dist[*it] == INT_MAX) { q.push(*it); } dist[*it] = min(dist[*it], dc); } } for (int j = 0; j < n; ++j) { if (dist[j] < INT_MAX) { s[i] += dist[j]; } } } for (int i = 0; i < n; ++i) { printf("%d ", s[i]); } } |