# | Submission time | Handle | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1073000 | 2024-08-24T08:20:09 Z | Ignut | Stations (IOI20_stations) | C++17 | 0 ms | 0 KB |
// Ignut #include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 1111; vector<int> tree[N]; vector<int> order; vector<int> dist; void dfs(int v, int par, int d) { order.push_back(v); for (int to : tree[v]) if (to != par) dfs(to, v); } vector<int> label(int n, int k, vector<int> u, vector<int> v) { order.clear(); for (int i = 0; i < n; i ++) { tree[i].clear(); } for (int i = 0; i < n - 1; i ++) { tree[u[i]].push_back(v[i]); tree[v[i]].push_back(u[i]); } vector<int> lbl(n); for (int i = 0; i < n; i ++) { vector<int> vec = {i + 1}; for (int to : tree[i]) { order.clear(); dfs(to, i); for (int val : order) vec.push_back(val + 1); order.clear(); } lbl[i] = 0; for (int val : vec) lbl[i] = lbl[i] * 10 + val; } return lbl; } int find_next_station(int s, int t, vector<int> c) { if (c.size() == 1) return c[0]; for (int val : c) if (val == t) return t; } static int max_label = 0; static int r, n, k, q; static std::vector<int> u, v, labels, answers; static std::map<int, int> reverse_labels; static std::vector<std::vector<int>> adjlist; static int s, t, w; static std::vector<int> c; int main() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); assert(scanf("%d", &r) == 1); for (int tc = 0; tc < r; tc++) { assert(scanf("%d%d", &n, &k) == 2); u.resize(n - 1); v.resize(n - 1); adjlist.clear(); adjlist.resize(n); for (int i = 0; i < n - 1; i++) { assert(scanf("%d%d", &u[i], &v[i]) == 2); adjlist[u[i]].push_back(v[i]); adjlist[v[i]].push_back(u[i]); } labels = label(n, k, u, v); if ((int)labels.size() != n) { printf("Number of labels not equal to %d\n", n); exit(0); } reverse_labels.clear(); for (int i = 0; i < n; i++) { if (labels[i] < 0 || labels[i] > k) { printf("Label not in range 0 to %d\n", k); exit(0); } if (reverse_labels.find(labels[i]) != reverse_labels.end()) { printf("Labels not unique\n"); exit(0); } reverse_labels[labels[i]] = i; if (labels[i] > max_label) { max_label = labels[i]; } } assert(scanf("%d", &q) == 1); for (int i = 0; i < q; i++) { assert(scanf("%d%d%d", &s, &t, &w) == 3); c.clear(); for (int v : adjlist[s]) { c.push_back(labels[v]); } std::sort(c.begin(), c.end()); int answer = find_next_station(labels[s], labels[t], c); if (!std::binary_search(c.begin(), c.end(), answer)) { printf("Label %d returned by find_next_station not found in c\n", answer); exit(0); } answers.push_back(reverse_labels[answer]); } } printf("%d\n", max_label); for (int index : answers) { printf("%d\n", index); } exit(0); } /* 1 8 1000000 0 1 1 4 2 3 3 4 4 5 4 6 6 7 5 0 4 4 2 5 5 3 7 7 2 5 3 3 7 4 */