#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<vector<int>> Adj; int main() { int n; cin >> n; vector<int> p(n); Adj.resize(n); for (int i = 0; i < n; i++) { cin >> p[i]; p[i]--; } for (int i =0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (p[j] < p[i]) { Adj[i].push_back(j); Adj[j].push_back(i); } } } for (int i = 0; i < n; i++) { vector<ll> dist(n); dist[i] = 0; queue<int> q; vector<bool> vis(n, false); q.push(i); vis[i] = true; ll res = 0ll; while (!q.empty()) { int v = q.front(); q.pop(); for (int u : Adj[v]) { if (!vis[u]) { vis[u] = true; dist[u] = dist[v] + 1; res += dist[u]; q.push(u); } } } cout << res << " "; } cout << '\n'; }
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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; vector<vector<int>> Adj; int main() { int n; cin >> n; vector<int> p(n); Adj.resize(n); for (int i = 0; i < n; i++) { cin >> p[i]; p[i]--; } for (int i =0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (p[j] < p[i]) { Adj[i].push_back(j); Adj[j].push_back(i); } } } for (int i = 0; i < n; i++) { vector<ll> dist(n); dist[i] = 0; queue<int> q; vector<bool> vis(n, false); q.push(i); vis[i] = true; ll res = 0ll; while (!q.empty()) { int v = q.front(); q.pop(); for (int u : Adj[v]) { if (!vis[u]) { vis[u] = true; dist[u] = dist[v] + 1; res += dist[u]; q.push(u); } } } cout << res << " "; } cout << '\n'; } |