#include <iostream>
#include <vector>
#include <algorithm>
#include <deque>
using namespace std;
vector<int> load_connections(int k) {
vector<int> res(1);
for (int i=0; i<k; i++) {
int val;
cin >> val;
res.push_back(val);
}
return res;
}
bool are_connected(vector<int>& graph, int a, int b) {
if (a < b) {
return graph[a] > graph[b];
} else {
return graph[a] < graph[b];
}
}
long sum_of_distances(vector<int>& graph, int s) {
vector<bool> visited(graph.size());
visited[s] = true;
deque<int> queue;
int TOKEN = -1;
queue.push_back(s);
queue.push_back(TOKEN);
int distance = 0;
long result = 0;
while (queue.size() > 1){
int next = queue.front();
queue.pop_front();
if (next == TOKEN) {
distance++;
queue.push_back(TOKEN);
continue;
}
result += distance;
for (int i=1; i<graph.size(); i++) {
if (!visited[i] && are_connected(graph, i, next)) {
visited[i] = true;
queue.push_back(i);
}
}
}
return result;
}
int main() {
int k;
cin >> k;
vector<int> graph = load_connections(k);
for (int i=1; i<=k; i++) {
std::cout << sum_of_distances(graph, i) << " ";
}
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 | #include <iostream> #include <vector> #include <algorithm> #include <deque> using namespace std; vector<int> load_connections(int k) { vector<int> res(1); for (int i=0; i<k; i++) { int val; cin >> val; res.push_back(val); } return res; } bool are_connected(vector<int>& graph, int a, int b) { if (a < b) { return graph[a] > graph[b]; } else { return graph[a] < graph[b]; } } long sum_of_distances(vector<int>& graph, int s) { vector<bool> visited(graph.size()); visited[s] = true; deque<int> queue; int TOKEN = -1; queue.push_back(s); queue.push_back(TOKEN); int distance = 0; long result = 0; while (queue.size() > 1){ int next = queue.front(); queue.pop_front(); if (next == TOKEN) { distance++; queue.push_back(TOKEN); continue; } result += distance; for (int i=1; i<graph.size(); i++) { if (!visited[i] && are_connected(graph, i, next)) { visited[i] = true; queue.push_back(i); } } } return result; } int main() { int k; cin >> k; vector<int> graph = load_connections(k); for (int i=1; i<=k; i++) { std::cout << sum_of_distances(graph, i) << " "; } return 0; } |
English