#include <cstdio> #include <queue> #include <vector> using namespace std; int p[200001]; vector<int> edge[200001]; int vis[200001]; int d[200001]; int main() { int n; scanf("%d", &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[i] > p[j]) { edge[i].push_back(j); edge[j].push_back(i); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { vis[j] = 0; d[j] = 0; } queue<int> Q; Q.push(i); while (!Q.empty()) { int u = Q.front(); vis[u] = 1; Q.pop(); for (int i = 0; i < edge[u].size(); i++) { int v = edge[u][i]; if (!vis[v]) { Q.push(v); vis[v] = 1; d[v] = d[u] + 1; } } } //printf("i = %d\n", i); for (int j = 0; j < n; j++) { //printf("%d ", d[j]); } //printf("\n"); int r = 0; for (int j = 0; j < n; j++) r += d[j]; printf("%d ", r); } printf("\n"); return 0; }
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | #include <cstdio> #include <queue> #include <vector> using namespace std; int p[200001]; vector<int> edge[200001]; int vis[200001]; int d[200001]; int main() { int n; scanf("%d", &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[i] > p[j]) { edge[i].push_back(j); edge[j].push_back(i); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { vis[j] = 0; d[j] = 0; } queue<int> Q; Q.push(i); while (!Q.empty()) { int u = Q.front(); vis[u] = 1; Q.pop(); for (int i = 0; i < edge[u].size(); i++) { int v = edge[u][i]; if (!vis[v]) { Q.push(v); vis[v] = 1; d[v] = d[u] + 1; } } } //printf("i = %d\n", i); for (int j = 0; j < n; j++) { //printf("%d ", d[j]); } //printf("\n"); int r = 0; for (int j = 0; j < n; j++) r += d[j]; printf("%d ", r); } printf("\n"); return 0; } |