#include <bits/stdc++.h>
using namespace std;
int length;
int *lines;
vector<vector<int>> adj;
void read() {
cin >> length;
lines = new int[length];
for (int i = 0; i < length; ++i) {
cin >> lines[i];
lines[i]--;
}
}
void createGraph() {
for (int i = 0; i < length; ++i) {
vector<int> neighbors;
for (int j = 0; j < length; ++j) {
if (i != j && i < j != lines[i] < lines[j]) {
neighbors.push_back(j);
}
}
adj.push_back(neighbors);
}
}
void showGraph() {
for (int i = 0; i < length; ++i) {
cout << i << ":";
for (auto neighbor: adj[i]) {
cout << " " << neighbor;
}
cout << endl;
}
cout << endl;
}
int bfs(int start) {
int sum = 0;
vector<int> distances;
distances.resize(length, -1);
distances[start] = 0;
queue<int> queue;
queue.push(start);
int current;
while (!queue.empty()) {
current = queue.front();
queue.pop();
sum += distances[current];
for (auto neighbor: adj[current]) {
if (distances[neighbor] < 0) {
distances[neighbor] = distances[current] + 1;
queue.push(neighbor);
}
}
}
return sum;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
read();
createGraph();
// showGraph();
for (int i = 0; i < length; ++i) {
cout << bfs(i) << " ";
}
cout << endl;
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 <bits/stdc++.h> using namespace std; int length; int *lines; vector<vector<int>> adj; void read() { cin >> length; lines = new int[length]; for (int i = 0; i < length; ++i) { cin >> lines[i]; lines[i]--; } } void createGraph() { for (int i = 0; i < length; ++i) { vector<int> neighbors; for (int j = 0; j < length; ++j) { if (i != j && i < j != lines[i] < lines[j]) { neighbors.push_back(j); } } adj.push_back(neighbors); } } void showGraph() { for (int i = 0; i < length; ++i) { cout << i << ":"; for (auto neighbor: adj[i]) { cout << " " << neighbor; } cout << endl; } cout << endl; } int bfs(int start) { int sum = 0; vector<int> distances; distances.resize(length, -1); distances[start] = 0; queue<int> queue; queue.push(start); int current; while (!queue.empty()) { current = queue.front(); queue.pop(); sum += distances[current]; for (auto neighbor: adj[current]) { if (distances[neighbor] < 0) { distances[neighbor] = distances[current] + 1; queue.push(neighbor); } } } return sum; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); read(); createGraph(); // showGraph(); for (int i = 0; i < length; ++i) { cout << bfs(i) << " "; } cout << endl; return 0; } |
English