#include <iostream> #include <string> #include <algorithm> #include <vector> #include <queue> using namespace std; void bfs(int v, vector<vector<int>> &G, vector<int> &dist) { queue<int> Q; Q.push(v); dist[v] = 0; while (!Q.empty()) { v = Q.front(); Q.pop(); for (int u : G[v]) { if (dist[u] == INT32_MAX) { dist[u] = dist[v] + 1; Q.push(u); } } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> end(n + 1); vector<int> dist(n + 1, INT32_MAX); for (int i = 1; i <= n; ++i) cin >> end[i]; vector<vector<int>> G(n + 1); for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { if ((j - i) * (end[j] - end[i]) < 0) { G[i].push_back(j); G[j].push_back(i); } } } for (int i = 1; i <= n; ++i) { bfs(i, G, dist); int ans = 0; for (int j = 1; j <= n; ++j) { if (dist[j] != INT32_MAX) ans += dist[j]; } cout << ans << " "; dist.assign(n + 1, INT32_MAX); } }
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 | #include <iostream> #include <string> #include <algorithm> #include <vector> #include <queue> using namespace std; void bfs(int v, vector<vector<int>> &G, vector<int> &dist) { queue<int> Q; Q.push(v); dist[v] = 0; while (!Q.empty()) { v = Q.front(); Q.pop(); for (int u : G[v]) { if (dist[u] == INT32_MAX) { dist[u] = dist[v] + 1; Q.push(u); } } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> end(n + 1); vector<int> dist(n + 1, INT32_MAX); for (int i = 1; i <= n; ++i) cin >> end[i]; vector<vector<int>> G(n + 1); for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { if ((j - i) * (end[j] - end[i]) < 0) { G[i].push_back(j); G[j].push_back(i); } } } for (int i = 1; i <= n; ++i) { bfs(i, G, dist); int ans = 0; for (int j = 1; j <= n; ++j) { if (dist[j] != INT32_MAX) ans += dist[j]; } cout << ans << " "; dist.assign(n + 1, INT32_MAX); } } |