#include <bits/stdc++.h> using namespace std; #define DEBUG #ifdef DEBUG #define D(x) x #else #define D(x) #endif long long bfs(int i, const vector<vector<int>> &graph); int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> permutation(n); for (auto &p : permutation) cin >> p; vector<vector<int>> graph(n); for (int i = 1; i <= size(graph); ++i) { for (int j = 1; j <= n; ++j) { if (i < j and permutation[i - 1] > permutation[j - 1] or i > j and permutation[i - 1] < permutation[j - 1]) graph[i - 1].push_back(j - 1); } } D( cerr << "graph" << endl; for (auto &l : graph) { for (auto e: l) cerr << e << ' '; cerr << endl; } ) for (int i = 0; i < size(graph); ++i) { cout << bfs(i, graph) << ' '; } } long long bfs(int i, const vector<vector<int>> &graph) { vector<bool> visited(size(graph)); queue<pair<int, int>> bfsQueue; bfsQueue.emplace(i, 0); visited[i] = true; long long result = 0; while (not bfsQueue.empty()) { auto [e, l] = bfsQueue.front(); bfsQueue.pop(); for (auto f : graph[e]) { if (visited[f]) continue; visited[f] = true; result += l + 1; bfsQueue.emplace(f, l + 1); } } return result; }
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 | #include <bits/stdc++.h> using namespace std; #define DEBUG #ifdef DEBUG #define D(x) x #else #define D(x) #endif long long bfs(int i, const vector<vector<int>> &graph); int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> permutation(n); for (auto &p : permutation) cin >> p; vector<vector<int>> graph(n); for (int i = 1; i <= size(graph); ++i) { for (int j = 1; j <= n; ++j) { if (i < j and permutation[i - 1] > permutation[j - 1] or i > j and permutation[i - 1] < permutation[j - 1]) graph[i - 1].push_back(j - 1); } } D( cerr << "graph" << endl; for (auto &l : graph) { for (auto e: l) cerr << e << ' '; cerr << endl; } ) for (int i = 0; i < size(graph); ++i) { cout << bfs(i, graph) << ' '; } } long long bfs(int i, const vector<vector<int>> &graph) { vector<bool> visited(size(graph)); queue<pair<int, int>> bfsQueue; bfsQueue.emplace(i, 0); visited[i] = true; long long result = 0; while (not bfsQueue.empty()) { auto [e, l] = bfsQueue.front(); bfsQueue.pop(); for (auto f : graph[e]) { if (visited[f]) continue; visited[f] = true; result += l + 1; bfsQueue.emplace(f, l + 1); } } return result; } |