output
stringlengths
52
181k
instruction
stringlengths
296
182k
#include <bits/stdc++.h> using namespace std; template <typename _T> inline void read(_T &f) { f = 0; _T fu = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); } while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); } f *= fu; } template <typename T> void print(T x) { if (x < 0) putchar('-'), x = -x; if (x < 10) putchar(x + 48); else print(x / 10), putchar(x % 10 + 48); } template <typename T> void print(T x, char t) { print(x); putchar(t); } const int N = 1005; double a[N][N], f[N], g[N], p[N], ans[N]; int used[N], vis[N]; int n; int main() { read(n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int x; read(x); a[i][j] = (double)x / 100; } } for (int i = 1; i <= n; i++) f[i] = p[i] = 1; ans[n] = 0; vis[n] = 1; for (int i = 1; i <= n; i++) { int id = 0; for (int j = 1; j <= n; j++) { if (vis[j] && !used[j]) { if (!id || ans[j] < ans[id]) id = j; } } if (!id) break; used[id] = 1; if (id == 1) { printf("%.10lf\n", ans[1]); return 0; } for (int j = 1; j <= n; j++) { if (used[j] || a[j][id] < 1e-6) continue; double nowp = p[j] * a[j][id]; p[j] *= (1 - a[j][id]); f[j] += ans[id] * nowp; g[j] += nowp; if (!vis[j]) vis[j] = 1, ans[j] = f[j] / g[j]; else ans[j] = min(ans[j], f[j] / g[j]); } } return 0; }
### Prompt Please formulate a Cpp solution to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename _T> inline void read(_T &f) { f = 0; _T fu = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); } while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); } f *= fu; } template <typename T> void print(T x) { if (x < 0) putchar('-'), x = -x; if (x < 10) putchar(x + 48); else print(x / 10), putchar(x % 10 + 48); } template <typename T> void print(T x, char t) { print(x); putchar(t); } const int N = 1005; double a[N][N], f[N], g[N], p[N], ans[N]; int used[N], vis[N]; int n; int main() { read(n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int x; read(x); a[i][j] = (double)x / 100; } } for (int i = 1; i <= n; i++) f[i] = p[i] = 1; ans[n] = 0; vis[n] = 1; for (int i = 1; i <= n; i++) { int id = 0; for (int j = 1; j <= n; j++) { if (vis[j] && !used[j]) { if (!id || ans[j] < ans[id]) id = j; } } if (!id) break; used[id] = 1; if (id == 1) { printf("%.10lf\n", ans[1]); return 0; } for (int j = 1; j <= n; j++) { if (used[j] || a[j][id] < 1e-6) continue; double nowp = p[j] * a[j][id]; p[j] *= (1 - a[j][id]); f[j] += ans[id] * nowp; g[j] += nowp; if (!vis[j]) vis[j] = 1, ans[j] = f[j] / g[j]; else ans[j] = min(ans[j], f[j] / g[j]); } } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 1005; int n; int p[N][N]; bool f[N]; double d[N], K[N], B[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) { scanf("%d", &p[i][j]); if (i == j) p[i][j]; } for (int i = 1; i <= n; ++i) { d[i] = 1e60; K[i] = 1; B[i] = 1; } d[n] = 0; while (1) { int x = -1; for (int i = 1; i <= n; ++i) if (!f[i] && (!~x || d[i] < d[x])) x = i; f[x] = 1; if (x == 1) break; for (int i = 1; i <= n; ++i) { if (f[i] || !p[i][x]) continue; B[i] += K[i] * 0.01 * p[i][x] * d[x]; K[i] *= 1 - 0.01 * p[i][x]; d[i] = min(d[i], B[i] / (1 - K[i])); } } printf("%.12f\n", d[1]); return 0; }
### Prompt Generate a cpp solution to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1005; int n; int p[N][N]; bool f[N]; double d[N], K[N], B[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) { scanf("%d", &p[i][j]); if (i == j) p[i][j]; } for (int i = 1; i <= n; ++i) { d[i] = 1e60; K[i] = 1; B[i] = 1; } d[n] = 0; while (1) { int x = -1; for (int i = 1; i <= n; ++i) if (!f[i] && (!~x || d[i] < d[x])) x = i; f[x] = 1; if (x == 1) break; for (int i = 1; i <= n; ++i) { if (f[i] || !p[i][x]) continue; B[i] += K[i] * 0.01 * p[i][x] * d[x]; K[i] *= 1 - 0.01 * p[i][x]; d[i] = min(d[i], B[i] / (1 - K[i])); } } printf("%.12f\n", d[1]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 1010; int a[maxn][maxn], vis[maxn]; int N; double f[maxn], prob[maxn], coef[maxn]; int main() { cin >> N; for (int i = 1; i <= N; i++) for (int j = 1; j <= N; j++) scanf("%d", &a[i][j]); for (int i = 1; i <= N; i++) f[i] = 1e9, prob[i] = 1, coef[i] = 0; f[N] = 0; for (int i = 1; i <= N; i++) { double S = 1e9; int now; for (int j = 1; j <= N; j++) if (!vis[j] && f[j] < S) S = f[j], now = j; vis[now] = 1; if (now == 1) { printf("%.15f\n", S); return 0; } for (int j = 1; j <= N; j++) if (!vis[j]) { coef[j] += S * prob[j] * 0.01 * a[j][now]; prob[j] *= 1.0 - 0.01 * a[j][now]; if (prob[j] < 1 - 1e-9) f[j] = (1.0 + coef[j]) / (1.0 - prob[j]); } } return 0; }
### Prompt Please formulate a Cpp solution to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 1010; int a[maxn][maxn], vis[maxn]; int N; double f[maxn], prob[maxn], coef[maxn]; int main() { cin >> N; for (int i = 1; i <= N; i++) for (int j = 1; j <= N; j++) scanf("%d", &a[i][j]); for (int i = 1; i <= N; i++) f[i] = 1e9, prob[i] = 1, coef[i] = 0; f[N] = 0; for (int i = 1; i <= N; i++) { double S = 1e9; int now; for (int j = 1; j <= N; j++) if (!vis[j] && f[j] < S) S = f[j], now = j; vis[now] = 1; if (now == 1) { printf("%.15f\n", S); return 0; } for (int j = 1; j <= N; j++) if (!vis[j]) { coef[j] += S * prob[j] * 0.01 * a[j][now]; prob[j] *= 1.0 - 0.01 * a[j][now]; if (prob[j] < 1 - 1e-9) f[j] = (1.0 + coef[j]) / (1.0 - prob[j]); } } return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, vis[1005]; double p[1005][1005], E[1005], dis[1005], P[1005]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) for (int j = 1, x; j <= n; j++) scanf("%d", &x), p[i][j] = (double)x / 100.0; dis[n] = 0; vis[n] = 1; for (int i = 1; i < n; i++) P[i] = 1 - p[i][n], E[i] = 1; for (int cas = 1; cas < n; cas++) { int u = 0; double mn = 1e18, tmp; for (int i = 1; i < n; i++) if (!vis[i]) { tmp = E[i] / (1 - P[i]); if (tmp < mn) u = i, mn = tmp; } dis[u] = mn; vis[u] = 1; for (int i = 1; i < n; i++) if (!vis[i]) E[i] += P[i] * p[i][u] * mn, P[i] *= 1 - p[i][u]; } return printf("%.13lf", dis[1]), 0; }
### Prompt Create a solution in CPP for the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, vis[1005]; double p[1005][1005], E[1005], dis[1005], P[1005]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) for (int j = 1, x; j <= n; j++) scanf("%d", &x), p[i][j] = (double)x / 100.0; dis[n] = 0; vis[n] = 1; for (int i = 1; i < n; i++) P[i] = 1 - p[i][n], E[i] = 1; for (int cas = 1; cas < n; cas++) { int u = 0; double mn = 1e18, tmp; for (int i = 1; i < n; i++) if (!vis[i]) { tmp = E[i] / (1 - P[i]); if (tmp < mn) u = i, mn = tmp; } dis[u] = mn; vis[u] = 1; for (int i = 1; i < n; i++) if (!vis[i]) E[i] += P[i] * p[i][u] * mn, P[i] *= 1 - p[i][u]; } return printf("%.13lf", dis[1]), 0; } ```
#include <bits/stdc++.h> using namespace std; constexpr int inf32 = 0x3f3f3f3f; constexpr long long inf64 = 0x3f3f3f3f3f3f3f3f; inline int read() { int first = 0, w = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while ('0' <= ch && ch <= '9') first = first * 10 + (ch - '0'), ch = getchar(); return w * first; } int main() { int n; cin >> n; int cnt = n; vector<vector<double>> p(n, vector<double>(n)); for (int u = 0; u < (n); ++u) for (int v = 0; v < (n); ++v) p[u][v] = read(), p[u][v] /= 100; vector<int> vis(n, false); vector<double> f(n), now(n, 1); auto calc = [&](int u) -> double { return (f[u] + now[u]) / (1 - now[u]); }; int u = n - 1; auto trans = [&]() -> void { if (u != n - 1) f[u] = calc(u); vis[u] = true, --cnt; for (int v = 0; v < (n); ++v) if (!vis[v]) { f[v] += now[v] * p[v][u] * (f[u] + 1); now[v] *= 1 - p[v][u]; } u = -1; }; for (trans(); cnt; trans()) for (int v = 0; v < (n); ++v) if (!vis[v] && (!~u || calc(v) < calc(u))) u = v; printf("%.12lf\n", f[0]); return 0; }
### Prompt Create a solution in cpp for the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; constexpr int inf32 = 0x3f3f3f3f; constexpr long long inf64 = 0x3f3f3f3f3f3f3f3f; inline int read() { int first = 0, w = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while ('0' <= ch && ch <= '9') first = first * 10 + (ch - '0'), ch = getchar(); return w * first; } int main() { int n; cin >> n; int cnt = n; vector<vector<double>> p(n, vector<double>(n)); for (int u = 0; u < (n); ++u) for (int v = 0; v < (n); ++v) p[u][v] = read(), p[u][v] /= 100; vector<int> vis(n, false); vector<double> f(n), now(n, 1); auto calc = [&](int u) -> double { return (f[u] + now[u]) / (1 - now[u]); }; int u = n - 1; auto trans = [&]() -> void { if (u != n - 1) f[u] = calc(u); vis[u] = true, --cnt; for (int v = 0; v < (n); ++v) if (!vis[v]) { f[v] += now[v] * p[v][u] * (f[u] + 1); now[v] *= 1 - p[v][u]; } u = -1; }; for (trans(); cnt; trans()) for (int v = 0; v < (n); ++v) if (!vis[v] && (!~u || calc(v) < calc(u))) u = v; printf("%.12lf\n", f[0]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 1003; int n, x, vis[N]; double P[N], dp[N], p[N][N]; inline void in(register int &x) { int f = 0; x = 0; char c = getchar(); while (c < '0' || c > '9') f |= c == '-', c = getchar(); while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); x = f ? -x : x; } int main() { in(n); if (n == 1) { puts("0"); return 0; } for (register int i = 1; i <= n; ++i) for (register int j = 1; j <= n; ++j) in(x), p[i][j] = x / 100.0; for (register int i = 1; i <= n; ++i) dp[i] = 1, P[i] = 1 - p[i][n]; dp[n] = 0, vis[n] = 1; for (register int i = 1; i <= n; ++i) { register int w = 0; double mi = 1e18; for (register int j = 1; j <= n; ++j) if (!vis[j] && dp[j] / (1 - P[j]) < mi) w = j, mi = dp[j] / (1 - P[j]); vis[w] = 1; if (w == 1) { printf("%.10lf\n", dp[1] / (1 - P[1])); return 0; } for (register int j = 1; j <= n; ++j) dp[j] += (dp[w] / (1 - P[w])) * p[j][w] * P[j], P[j] *= (1 - p[j][w]); } }
### Prompt Please create a solution in Cpp to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1003; int n, x, vis[N]; double P[N], dp[N], p[N][N]; inline void in(register int &x) { int f = 0; x = 0; char c = getchar(); while (c < '0' || c > '9') f |= c == '-', c = getchar(); while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); x = f ? -x : x; } int main() { in(n); if (n == 1) { puts("0"); return 0; } for (register int i = 1; i <= n; ++i) for (register int j = 1; j <= n; ++j) in(x), p[i][j] = x / 100.0; for (register int i = 1; i <= n; ++i) dp[i] = 1, P[i] = 1 - p[i][n]; dp[n] = 0, vis[n] = 1; for (register int i = 1; i <= n; ++i) { register int w = 0; double mi = 1e18; for (register int j = 1; j <= n; ++j) if (!vis[j] && dp[j] / (1 - P[j]) < mi) w = j, mi = dp[j] / (1 - P[j]); vis[w] = 1; if (w == 1) { printf("%.10lf\n", dp[1] / (1 - P[1])); return 0; } for (register int j = 1; j <= n; ++j) dp[j] += (dp[w] / (1 - P[w])) * p[j][w] * P[j], P[j] *= (1 - p[j][w]); } } ```
#include <bits/stdc++.h> using namespace std; const int N = 1e3 + 5; bool vis[N]; int n; double f[N]; double p[N][N], pro[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1, tmp; j <= n; j++) { scanf("%d", &tmp); p[i][j] = 1.0 * tmp / 100.0; } } if (n == 1) { printf("0\n"); return 0; } vis[n] = true; for (int i = 1; i < n; i++) { f[i] = 1; pro[i] = 1 - p[i][n]; } for (int i = 1; i <= n; i++) { double minn = 1e18 + 7; int pos; for (int j = 1; j <= n; j++) { if (!vis[j] && f[j] / (1 - pro[j]) < minn) { minn = f[j] / (1 - pro[j]); pos = j; } } if (pos == 1) { printf("%.12lf\n", f[1] / (1 - pro[1])); return 0; } vis[pos] = true; for (int j = 1; j <= n; j++) { f[j] += f[pos] / (1 - pro[pos]) * p[j][pos] * pro[j]; pro[j] *= (1 - p[j][pos]); } } return 0; }
### Prompt Create a solution in Cpp for the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e3 + 5; bool vis[N]; int n; double f[N]; double p[N][N], pro[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1, tmp; j <= n; j++) { scanf("%d", &tmp); p[i][j] = 1.0 * tmp / 100.0; } } if (n == 1) { printf("0\n"); return 0; } vis[n] = true; for (int i = 1; i < n; i++) { f[i] = 1; pro[i] = 1 - p[i][n]; } for (int i = 1; i <= n; i++) { double minn = 1e18 + 7; int pos; for (int j = 1; j <= n; j++) { if (!vis[j] && f[j] / (1 - pro[j]) < minn) { minn = f[j] / (1 - pro[j]); pos = j; } } if (pos == 1) { printf("%.12lf\n", f[1] / (1 - pro[1])); return 0; } vis[pos] = true; for (int j = 1; j <= n; j++) { f[j] += f[pos] / (1 - pro[pos]) * p[j][pos] * pro[j]; pro[j] *= (1 - p[j][pos]); } } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 100; const double eps = 1e-9; const double pi = 4 * atan(1.0); const int N = 1010; bool used[N]; double dp[N], sum[N], prob[N]; double p[N][N]; int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { scanf("%lf", &p[j][i]); p[j][i] /= 100.0; } } for (int i = 0; i < n; ++i) { dp[i] = 1e100; prob[i] = 1.0; } dp[n - 1] = 0; for (int i = 0; i < n; ++i) { int v = -1; if (i == 0) { v = n - 1; } else { for (int j = 0; j < n; ++j) { if (!used[j]) { if (fabs(prob[j] - 1.0) < eps) { dp[j] = 1e100; } else { dp[j] = (sum[j] + prob[j]) / (1.0 - prob[j]); } if (v == -1 || dp[j] < dp[v]) { v = j; } } } } used[v] = true; if (dp[v] > 1e50) { continue; } for (int j = 0; j < n; ++j) { if (used[j]) { continue; } sum[j] += prob[j] * p[v][j] * (dp[v] + 1.0); prob[j] *= (1 - p[v][j]); } } printf("%.18lf\n", dp[0]); return 0; }
### Prompt Develop a solution in CPP to the problem described below: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 100; const double eps = 1e-9; const double pi = 4 * atan(1.0); const int N = 1010; bool used[N]; double dp[N], sum[N], prob[N]; double p[N][N]; int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { scanf("%lf", &p[j][i]); p[j][i] /= 100.0; } } for (int i = 0; i < n; ++i) { dp[i] = 1e100; prob[i] = 1.0; } dp[n - 1] = 0; for (int i = 0; i < n; ++i) { int v = -1; if (i == 0) { v = n - 1; } else { for (int j = 0; j < n; ++j) { if (!used[j]) { if (fabs(prob[j] - 1.0) < eps) { dp[j] = 1e100; } else { dp[j] = (sum[j] + prob[j]) / (1.0 - prob[j]); } if (v == -1 || dp[j] < dp[v]) { v = j; } } } } used[v] = true; if (dp[v] > 1e50) { continue; } for (int j = 0; j < n; ++j) { if (used[j]) { continue; } sum[j] += prob[j] * p[v][j] * (dp[v] + 1.0); prob[j] *= (1 - p[v][j]); } } printf("%.18lf\n", dp[0]); return 0; } ```
#include <bits/stdc++.h> using namespace std; int const N = 1001; bool vis[N]; double E[N], E2[N], P[N], A[N][N]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%lf", &A[i][j]); A[i][j] /= 100; } } int cur = n - 1; vis[n - 1] = true; while (cur != 0) { int nxt = -1; long double best_value = 1000000000; for (int i = 0; i < n; i++) { if (vis[i]) continue; if (P[i] == 0 && A[i][cur] == 0) continue; long double new_P = A[i][cur] * (1 - P[i]); E[i] = (new_P * (E2[cur] + 1) + P[i] * E[i]) / (new_P + P[i]); P[i] += new_P; E2[i] = 1 / P[i] + E[i] - 1; if (E2[i] < best_value) { nxt = i; best_value = E2[i]; } } vis[nxt] = true; cur = nxt; } printf("%9.14lf", E2[0]); return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int const N = 1001; bool vis[N]; double E[N], E2[N], P[N], A[N][N]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%lf", &A[i][j]); A[i][j] /= 100; } } int cur = n - 1; vis[n - 1] = true; while (cur != 0) { int nxt = -1; long double best_value = 1000000000; for (int i = 0; i < n; i++) { if (vis[i]) continue; if (P[i] == 0 && A[i][cur] == 0) continue; long double new_P = A[i][cur] * (1 - P[i]); E[i] = (new_P * (E2[cur] + 1) + P[i] * E[i]) / (new_P + P[i]); P[i] += new_P; E2[i] = 1 / P[i] + E[i] - 1; if (E2[i] < best_value) { nxt = i; best_value = E2[i]; } } vis[nxt] = true; cur = nxt; } printf("%9.14lf", E2[0]); return 0; } ```
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target( \ "avx,avx2,fma,sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; int MOD = 1e9 + 7; vector<vector<double> > p; vector<int> used; int n; vector<double> ans; vector<double> sm; vector<double> pr; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout << fixed << setprecision(20); cin >> n; p.resize(n); used.resize(n); for (int i = 0; i < n; i++) { p[i].resize(n); for (int j = 0; j < n; j++) { int pp; cin >> pp; p[i][j] = (double)pp / (double)100; } } ans.resize(n); sm.resize(n); pr.resize(n, 1); int nw = n - 1; for (int i = 0; i < n; i++) { double mn = MOD; int mnid = -1; for (int j = 0; j < n - 1; j++) { if (!used[j]) { sm[j] += pr[j] * p[j][nw] * (ans[nw] + 1); pr[j] *= (1 - p[j][nw]); if (pr[j] == 1) { ans[j] = MOD; } else { ans[j] = (sm[j] + pr[j]) / (1 - pr[j]); } mn = min(mn, ans[j]); if (mn == ans[j]) { mnid = j; } } } if (mnid == -1) break; used[mnid] = 1; nw = mnid; } cout << ans[0] << endl; }
### Prompt Your task is to create a Cpp solution to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target( \ "avx,avx2,fma,sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; int MOD = 1e9 + 7; vector<vector<double> > p; vector<int> used; int n; vector<double> ans; vector<double> sm; vector<double> pr; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout << fixed << setprecision(20); cin >> n; p.resize(n); used.resize(n); for (int i = 0; i < n; i++) { p[i].resize(n); for (int j = 0; j < n; j++) { int pp; cin >> pp; p[i][j] = (double)pp / (double)100; } } ans.resize(n); sm.resize(n); pr.resize(n, 1); int nw = n - 1; for (int i = 0; i < n; i++) { double mn = MOD; int mnid = -1; for (int j = 0; j < n - 1; j++) { if (!used[j]) { sm[j] += pr[j] * p[j][nw] * (ans[nw] + 1); pr[j] *= (1 - p[j][nw]); if (pr[j] == 1) { ans[j] = MOD; } else { ans[j] = (sm[j] + pr[j]) / (1 - pr[j]); } mn = min(mn, ans[j]); if (mn == ans[j]) { mnid = j; } } } if (mnid == -1) break; used[mnid] = 1; nw = mnid; } cout << ans[0] << endl; } ```
#include <bits/stdc++.h> using namespace std; const int N = 1100; int n; bool v[N]; double f[N][N], prod[N], g[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { scanf("%lf", &f[i][j]); f[i][j] /= 100.0; } } if (n == 1) return puts("0") & 0; for (int i = 1; i < n; i++) prod[i] = 1 - f[i][n], g[i] = 1; v[n] = 1; for (int p = 1; p <= n; p++) { double low = 1e9; int x; for (int i = 1; i <= n; i++) if (g[i] / (1 - prod[i]) < low && !v[i]) low = g[i] / (1 - prod[i]), x = i; if (x == 1) return printf("%.10lf", low) & 0; v[x] = 1; for (int i = 1; i <= n; i++) { if (v[i]) continue; g[i] += low * f[i][x] * prod[i]; prod[i] *= (1 - f[i][x]); } } return 0; }
### Prompt Develop a solution in cpp to the problem described below: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1100; int n; bool v[N]; double f[N][N], prod[N], g[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { scanf("%lf", &f[i][j]); f[i][j] /= 100.0; } } if (n == 1) return puts("0") & 0; for (int i = 1; i < n; i++) prod[i] = 1 - f[i][n], g[i] = 1; v[n] = 1; for (int p = 1; p <= n; p++) { double low = 1e9; int x; for (int i = 1; i <= n; i++) if (g[i] / (1 - prod[i]) < low && !v[i]) low = g[i] / (1 - prod[i]), x = i; if (x == 1) return printf("%.10lf", low) & 0; v[x] = 1; for (int i = 1; i <= n; i++) { if (v[i]) continue; g[i] += low * f[i][x] * prod[i]; prod[i] *= (1 - f[i][x]); } } return 0; } ```
#include <bits/stdc++.h> int n, m; double p[1005][1005]; double dist[1005]; double qhy[1005], zyg[1005]; bool flag[1005]; using namespace std; void standing_by() { int i, j; scanf("%d", &n); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) { scanf("%lf", &p[i][j]); p[i][j] /= 100; } for (i = 0; i <= n; i++) { dist[i] = -1; qhy[i] = 1; } dist[n] = 0; } void complete() { int i, j, k; for (i = 1; i < n; i++) { for (j = 1, k = 0; j <= n; j++) if (!flag[j] && dist[j] >= 0 && (dist[j] <= dist[k] || dist[k] < 0)) k = j; flag[k] = true; for (j = 1; j <= n; j++) if (!flag[j]) { zyg[j] += qhy[j] * p[j][k] * (1 + dist[k]); qhy[j] = qhy[j] * (1 - p[j][k]); if (1 - qhy[j] > 0) dist[j] = (zyg[j] + qhy[j]) / (1 - qhy[j]); else if (zyg[j] > 0) dist[j] = zyg[j]; } } printf("%.10lf\n", dist[1]); } int main() { standing_by(); complete(); return 0; }
### Prompt In cpp, your task is to solve the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> int n, m; double p[1005][1005]; double dist[1005]; double qhy[1005], zyg[1005]; bool flag[1005]; using namespace std; void standing_by() { int i, j; scanf("%d", &n); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) { scanf("%lf", &p[i][j]); p[i][j] /= 100; } for (i = 0; i <= n; i++) { dist[i] = -1; qhy[i] = 1; } dist[n] = 0; } void complete() { int i, j, k; for (i = 1; i < n; i++) { for (j = 1, k = 0; j <= n; j++) if (!flag[j] && dist[j] >= 0 && (dist[j] <= dist[k] || dist[k] < 0)) k = j; flag[k] = true; for (j = 1; j <= n; j++) if (!flag[j]) { zyg[j] += qhy[j] * p[j][k] * (1 + dist[k]); qhy[j] = qhy[j] * (1 - p[j][k]); if (1 - qhy[j] > 0) dist[j] = (zyg[j] + qhy[j]) / (1 - qhy[j]); else if (zyg[j] > 0) dist[j] = zyg[j]; } } printf("%.10lf\n", dist[1]); } int main() { standing_by(); complete(); return 0; } ```
#include <bits/stdc++.h> using namespace std; inline int max(int a, int b) { return a < b ? b : a; } inline int min(int a, int b) { return a > b ? b : a; } inline long long max(long long a, long long b) { return a < b ? b : a; } inline long long min(long long a, long long b) { return a > b ? b : a; } const int mod = 1e9 + 7; const int N = 1e6 + 10; const long long INF = 1e18; long double G[1005][1005]; long double ans[1005]; int u[1005]; long double EPS = 1e-12; long double cur[1005], sum[1005]; vector<int> s; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { int x; scanf("%d", &x); G[i][j] = x * 1. / 100; } if (n == 1) { printf("%lf\n", 0.0); exit(0); } for (int i = 0; i < n - 1; ++i) sum[i] = 1; for (int i = 0; i < n - 1; ++i) if (G[i][n - 1] == 100) u[i] = 1; else cur[i] = 1 - G[i][n - 1]; int it = 0; while (!u[0] && it < n + 5) { s.clear(); it++; long double mx = INF; for (int i = 0; i < n - 1; ++i) if (u[i] == 0) { long double x = sum[i] / (1 - cur[i]); if (abs(x - mx) < EPS) s.push_back(i); else if (x < mx) { s.clear(); mx = x; s.push_back(i); } } for (int i = 0; i < s.size(); ++i) { ans[s[i]] = mx; u[s[i]] = 1; } for (int i = 0; i < n - 1; ++i) if (u[i] == 0) { long double x = 1; for (int j = 0; j < s.size(); ++j) x *= (1 - G[i][s[j]]); sum[i] += cur[i] * (1 - x) * mx; cur[i] *= x; } } printf("%.9lf\n", (double)ans[0]); return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int max(int a, int b) { return a < b ? b : a; } inline int min(int a, int b) { return a > b ? b : a; } inline long long max(long long a, long long b) { return a < b ? b : a; } inline long long min(long long a, long long b) { return a > b ? b : a; } const int mod = 1e9 + 7; const int N = 1e6 + 10; const long long INF = 1e18; long double G[1005][1005]; long double ans[1005]; int u[1005]; long double EPS = 1e-12; long double cur[1005], sum[1005]; vector<int> s; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { int x; scanf("%d", &x); G[i][j] = x * 1. / 100; } if (n == 1) { printf("%lf\n", 0.0); exit(0); } for (int i = 0; i < n - 1; ++i) sum[i] = 1; for (int i = 0; i < n - 1; ++i) if (G[i][n - 1] == 100) u[i] = 1; else cur[i] = 1 - G[i][n - 1]; int it = 0; while (!u[0] && it < n + 5) { s.clear(); it++; long double mx = INF; for (int i = 0; i < n - 1; ++i) if (u[i] == 0) { long double x = sum[i] / (1 - cur[i]); if (abs(x - mx) < EPS) s.push_back(i); else if (x < mx) { s.clear(); mx = x; s.push_back(i); } } for (int i = 0; i < s.size(); ++i) { ans[s[i]] = mx; u[s[i]] = 1; } for (int i = 0; i < n - 1; ++i) if (u[i] == 0) { long double x = 1; for (int j = 0; j < s.size(); ++j) x *= (1 - G[i][s[j]]); sum[i] += cur[i] * (1 - x) * mx; cur[i] *= x; } } printf("%.9lf\n", (double)ans[0]); return 0; } ```
#include <bits/stdc++.h> const int N = 1054; int n; bool ok[N]; double p[N][N], f[N], acc[N], rem[N]; inline int find() { int i, v = n; for (i = 0; i < n; ++i) if (!ok[i] && f[i] < f[v]) v = i; return v; } int main() { int i, j, x; scanf("%d", &n); for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) scanf("%d", &x), p[i][j] = .01 * x; memset(f, 127, sizeof f), f[n - 1] = 0.; std::fill(acc, acc + n, 1.), std::fill(rem, rem + n, 1.); for (; (x = find()) != n;) { ok[x] = true; for (i = 0; i < n; ++i) if (!ok[i]) acc[i] += rem[i] * p[i][x] * f[x], rem[i] *= 1. - p[i][x], f[i] = acc[i] / (1. - rem[i]); } printf("%.12lg\n", *f); return 0; }
### Prompt Construct a CPP code solution to the problem outlined: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> const int N = 1054; int n; bool ok[N]; double p[N][N], f[N], acc[N], rem[N]; inline int find() { int i, v = n; for (i = 0; i < n; ++i) if (!ok[i] && f[i] < f[v]) v = i; return v; } int main() { int i, j, x; scanf("%d", &n); for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) scanf("%d", &x), p[i][j] = .01 * x; memset(f, 127, sizeof f), f[n - 1] = 0.; std::fill(acc, acc + n, 1.), std::fill(rem, rem + n, 1.); for (; (x = find()) != n;) { ok[x] = true; for (i = 0; i < n; ++i) if (!ok[i]) acc[i] += rem[i] * p[i][x] * f[x], rem[i] *= 1. - p[i][x], f[i] = acc[i] / (1. - rem[i]); } printf("%.12lg\n", *f); return 0; } ```
#include <bits/stdc++.h> inline int read() { int x = 0; char c = getchar(); while (!isdigit(c)) c = getchar(); while (isdigit(c)) x = (x << 3) + (x << 1) + c - 48, c = getchar(); return x; } const int N = 1e3 + 7; int n; double p[N][N], E[N], f[N]; bool vis[N]; int main() { n = read(); if (n == 1) return puts("0"), 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { p[i][j] = 1.0 * read() / 100; } } for (int i = 1; i < n; ++i) E[i] = 1, f[i] = 1 - p[i][n]; vis[n] = 1; for (int i = 1; i <= n; ++i) { double min = 1e18; int pos = 0; for (int j = 1; j <= n; ++j) { if (vis[j]) continue; if (E[j] / (1 - f[j]) < min) min = E[j] / (1 - f[j]), pos = j; } if (pos == 1) return printf("%.10lf\n", E[1] / (1 - f[1])), 0; vis[pos] = 1; for (int j = 1; j <= n; ++j) { E[j] += E[pos] / (1 - f[pos]) * p[j][pos] * f[j], f[j] *= (1 - p[j][pos]); } } return 0; }
### Prompt Please create a solution in CPP to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> inline int read() { int x = 0; char c = getchar(); while (!isdigit(c)) c = getchar(); while (isdigit(c)) x = (x << 3) + (x << 1) + c - 48, c = getchar(); return x; } const int N = 1e3 + 7; int n; double p[N][N], E[N], f[N]; bool vis[N]; int main() { n = read(); if (n == 1) return puts("0"), 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { p[i][j] = 1.0 * read() / 100; } } for (int i = 1; i < n; ++i) E[i] = 1, f[i] = 1 - p[i][n]; vis[n] = 1; for (int i = 1; i <= n; ++i) { double min = 1e18; int pos = 0; for (int j = 1; j <= n; ++j) { if (vis[j]) continue; if (E[j] / (1 - f[j]) < min) min = E[j] / (1 - f[j]), pos = j; } if (pos == 1) return printf("%.10lf\n", E[1] / (1 - f[1])), 0; vis[pos] = 1; for (int j = 1; j <= n; ++j) { E[j] += E[pos] / (1 - f[pos]) * p[j][pos] * f[j], f[j] *= (1 - p[j][pos]); } } return 0; } ```
#include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; long long powmod(long long a, long long b) { long long res = 1; a %= mod; for (; b; b >>= 1) { if (b & 1) res = res * a % mod; a = a * a % mod; } return res; } const int N = 1010; int n, p[N][N], vis[N]; long double E[N], prob[N], coef[N]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &p[i][j]); for (int i = 0; i < n; i++) E[i] = 1e30, prob[i] = 1, coef[i] = 0; E[n - 1] = 0; for (int k = 0; k < n; k++) { long double mv = 1e30; int ps = -1; for (int i = 0; i < n; i++) if (!vis[i] && E[i] < mv) mv = E[i], ps = i; vis[ps] = 1; if (ps == 0) { printf("%.15f\n", (double)E[0]); return 0; } for (int i = 0; i < n; i++) if (!vis[i]) { coef[i] += E[ps] * prob[i] * 0.01 * p[i][ps]; prob[i] *= (1 - 0.01 * p[i][ps]); if (prob[i] < 1 - 1e-6) E[i] = (1 + coef[i]) / (1 - prob[i]); } } assert(0); }
### Prompt Please provide a cpp coded solution to the problem described below: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; long long powmod(long long a, long long b) { long long res = 1; a %= mod; for (; b; b >>= 1) { if (b & 1) res = res * a % mod; a = a * a % mod; } return res; } const int N = 1010; int n, p[N][N], vis[N]; long double E[N], prob[N], coef[N]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &p[i][j]); for (int i = 0; i < n; i++) E[i] = 1e30, prob[i] = 1, coef[i] = 0; E[n - 1] = 0; for (int k = 0; k < n; k++) { long double mv = 1e30; int ps = -1; for (int i = 0; i < n; i++) if (!vis[i] && E[i] < mv) mv = E[i], ps = i; vis[ps] = 1; if (ps == 0) { printf("%.15f\n", (double)E[0]); return 0; } for (int i = 0; i < n; i++) if (!vis[i]) { coef[i] += E[ps] * prob[i] * 0.01 * p[i][ps]; prob[i] *= (1 - 0.01 * p[i][ps]); if (prob[i] < 1 - 1e-6) E[i] = (1 + coef[i]) / (1 - prob[i]); } } assert(0); } ```
#include <bits/stdc++.h> using namespace std; const int N = 1010; int n, vis[N]; double p[N][N], f[N], a[N], b[N], c[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { int x; scanf("%d", &x); p[i][j] = x / 100.0; } vis[n] = 1; for (int i = 1; i < n; i++) a[i] = 1, b[i] = p[i][n], c[i] = 1 - p[i][n]; for (int i = 2; i <= n; i++) { double mn = 1e9; int x; for (int j = 1; j <= n; j++) if (!vis[j] && mn * b[j] > a[j]) mn = a[j] / b[j], x = j; f[x] = a[x] / b[x]; vis[x] = 1; for (int j = 1; j <= n; j++) if (!vis[j]) { a[j] += c[j] * p[j][x] * f[x]; c[j] *= 1 - p[j][x]; b[j] = 1 - c[j]; } } printf("%.9lf\n", f[1]); return 0; }
### Prompt Please formulate a CPP solution to the following problem: The scientists have recently discovered wormholes β€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i, j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day. Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists. Input The first line of the input contains a single integer n (1 ≀ n ≀ 1000) β€” the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100. Output Print a single real value β€” the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 100 50 50 0 100 80 0 0 100 Output 1.750000000000000 Input 2 100 30 40 100 Output 3.333333333333333 Note In the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is <image>. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1010; int n, vis[N]; double p[N][N], f[N], a[N], b[N], c[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { int x; scanf("%d", &x); p[i][j] = x / 100.0; } vis[n] = 1; for (int i = 1; i < n; i++) a[i] = 1, b[i] = p[i][n], c[i] = 1 - p[i][n]; for (int i = 2; i <= n; i++) { double mn = 1e9; int x; for (int j = 1; j <= n; j++) if (!vis[j] && mn * b[j] > a[j]) mn = a[j] / b[j], x = j; f[x] = a[x] / b[x]; vis[x] = 1; for (int j = 1; j <= n; j++) if (!vis[j]) { a[j] += c[j] * p[j][x] * f[x]; c[j] *= 1 - p[j][x]; b[j] = 1 - c[j]; } } printf("%.9lf\n", f[1]); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; int n, S, T, a[maxn], b[maxn], cir[maxn], cnt; int fa[maxn], dep[maxn], head[maxn], to[maxn << 1], nxt[maxn << 1], tot; bool inc[maxn], vis[maxn]; inline bool judge(int x) { return a[x] == b[x]; } inline void add_edge(int x, int y) { to[++tot] = y, nxt[tot] = head[x], head[x] = tot; } void dfs(int x, int ff) { dep[x] = dep[ff] + 1, fa[x] = ff; for (int i = head[x]; i; i = nxt[i]) if (to[i] != ff) dfs(to[i], x); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) S = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) T = i; } int x, y, u, v, sz, d, cov; bool fl; for (int i = 1; i < n; i++) { scanf("%d%d", &x, &y); add_edge(x, y), add_edge(y, x); } dfs(T, 0), x = S; while (fa[x]) swap(a[x], a[fa[x]]), vis[x] = 1, x = fa[x]; vis[T] = 1, fl = 1; for (int i = 1; i <= n; i++) if (!judge(i)) { fl = 0; break; } if (fl) return printf("0 %d\n", dep[S] - 1), 0; u = v = 0; for (int i = 1; i <= n; i++) if (!judge(i) && dep[i] > dep[u]) u = i; for (x = u; !judge(x); x = fa[x]) inc[x] = 1, cir[cnt++] = x; for (int i = 1; i <= n; i++) if (!judge(i) && !inc[i] && dep[i] > dep[v]) v = i; sz = cnt; if (v) { for (y = v; !judge(y); y = fa[y]) { if (inc[y]) return puts("-1"), 0; inc[y] = 1, cir[cnt++] = y; } if (y != x) return puts("-1"), 0; reverse(cir + sz, cir + cnt); } else y = v = x; for (int i = 1; i <= n; i++) if (!judge(i) && !inc[i]) return puts("-1"), 0; for (d = 1; d < cnt; d++) if (a[cir[d]] == b[cir[0]]) break; for (int i = 0; i < cnt; i++) if (a[cir[(i + d) % cnt]] != b[cir[i]]) return puts("-1"), 0; if (u > v) swap(u, v); printf("%d %d ", u, v); for (int i = S; i; i = fa[i]) vis[i] = 1; cov = 0; for (int i = 0; i < cnt; i++) cov += vis[cir[i]]; fl = 0; for (int i = 0; i < sz; i++) if (vis[cir[i]]) { fl = 1; break; } long long ans = dep[S] - 1; if (cov) { if (!fl) d = cnt - d; ans += min((long long)d * (cnt + 1), (long long)(cnt - d) * (cnt + 1) - 2 * cov); } else { ans += (long long)min(d, cnt - d) * (cnt + 1); while (!vis[x]) ans += 2, x = fa[x]; } printf("%lld\n", ans); return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; int n, S, T, a[maxn], b[maxn], cir[maxn], cnt; int fa[maxn], dep[maxn], head[maxn], to[maxn << 1], nxt[maxn << 1], tot; bool inc[maxn], vis[maxn]; inline bool judge(int x) { return a[x] == b[x]; } inline void add_edge(int x, int y) { to[++tot] = y, nxt[tot] = head[x], head[x] = tot; } void dfs(int x, int ff) { dep[x] = dep[ff] + 1, fa[x] = ff; for (int i = head[x]; i; i = nxt[i]) if (to[i] != ff) dfs(to[i], x); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) S = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) T = i; } int x, y, u, v, sz, d, cov; bool fl; for (int i = 1; i < n; i++) { scanf("%d%d", &x, &y); add_edge(x, y), add_edge(y, x); } dfs(T, 0), x = S; while (fa[x]) swap(a[x], a[fa[x]]), vis[x] = 1, x = fa[x]; vis[T] = 1, fl = 1; for (int i = 1; i <= n; i++) if (!judge(i)) { fl = 0; break; } if (fl) return printf("0 %d\n", dep[S] - 1), 0; u = v = 0; for (int i = 1; i <= n; i++) if (!judge(i) && dep[i] > dep[u]) u = i; for (x = u; !judge(x); x = fa[x]) inc[x] = 1, cir[cnt++] = x; for (int i = 1; i <= n; i++) if (!judge(i) && !inc[i] && dep[i] > dep[v]) v = i; sz = cnt; if (v) { for (y = v; !judge(y); y = fa[y]) { if (inc[y]) return puts("-1"), 0; inc[y] = 1, cir[cnt++] = y; } if (y != x) return puts("-1"), 0; reverse(cir + sz, cir + cnt); } else y = v = x; for (int i = 1; i <= n; i++) if (!judge(i) && !inc[i]) return puts("-1"), 0; for (d = 1; d < cnt; d++) if (a[cir[d]] == b[cir[0]]) break; for (int i = 0; i < cnt; i++) if (a[cir[(i + d) % cnt]] != b[cir[i]]) return puts("-1"), 0; if (u > v) swap(u, v); printf("%d %d ", u, v); for (int i = S; i; i = fa[i]) vis[i] = 1; cov = 0; for (int i = 0; i < cnt; i++) cov += vis[cir[i]]; fl = 0; for (int i = 0; i < sz; i++) if (vis[cir[i]]) { fl = 1; break; } long long ans = dep[S] - 1; if (cov) { if (!fl) d = cnt - d; ans += min((long long)d * (cnt + 1), (long long)(cnt - d) * (cnt + 1) - 2 * cov); } else { ans += (long long)min(d, cnt - d) * (cnt + 1); while (!vis[x]) ans += 2, x = fa[x]; } printf("%lld\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<int> v[200010], circle; int fa[200010], dep[200010], a[200010], b[200010], n, rt, vs, vt, h1, h2; bool vis[200010], bo[200010]; inline int rd() { int x = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) ; for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; return x; } inline void dfs(int x) { for (int i = 0, siz = v[x].size(); i < siz; i++) { int t = v[x][i]; if (t == fa[x]) continue; dep[t] = dep[x] + 1; fa[t] = x; dfs(t); } } inline bool gao() { int p = 0, q = 0; bool flag = true; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return true; for (int hh = p; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i] && dep[i] > dep[q]) q = i; if (q) { reverse(circle.begin(), circle.end()); flag = false; for (int hh = q; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); } else q = fa[circle.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i]) return false; int h1 = p, h2 = q; for (; h1 != h2; h1 = fa[h1]) if (dep[h1] < dep[h2]) swap(h1, h2); rt = h1; if (circle.size() != dep[p] + dep[q] - dep[rt] * 2) return false; vs = p; vt = q; if (flag) reverse(circle.begin(), circle.end()); return true; } int main() { n = rd(); for (int i = 1; i <= n; i++) if (!(a[i] = rd())) h1 = i; for (int i = 1; i <= n; i++) if (!(b[i] = rd())) h2 = i; for (int i = 1; i < n; i++) { int x = rd(), y = rd(); v[x].push_back(y); v[y].push_back(x); } dep[0] = -1; dfs(h2); for (int hh = h1; hh != h2; hh = fa[hh]) swap(a[hh], a[fa[hh]]); long long ans = dep[h1]; if (!gao()) { puts("-1"); return 0; } if (!circle.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, siz = circle.size(); for (int i = 0; i < siz; i++) if (b[circle[i]] == a[circle[0]]) gap = i; for (int i = 0; i < siz; i++) if (b[circle[(i + gap) % siz]] != a[circle[i]]) { puts("-1"); return 0; } for (int i = h1; i; i = fa[i]) vis[i] = true; if (vis[circle[0]] || vis[circle.back()]) { int now = siz; for (int i = 0; i < siz; i++) if (!vis[circle[i]]) { now = i; break; } ans = ans - now + min((long long)gap * (siz + 1) + now, abs((long long)(siz - gap) * (siz + 1) - now)); } else ans = (ans + (long long)min(gap, siz - gap) * (siz + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (vs > vt) swap(vs, vt); printf("%d %d %I64d\n", vs, vt, ans); return 0; }
### Prompt Create a solution in cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<int> v[200010], circle; int fa[200010], dep[200010], a[200010], b[200010], n, rt, vs, vt, h1, h2; bool vis[200010], bo[200010]; inline int rd() { int x = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) ; for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; return x; } inline void dfs(int x) { for (int i = 0, siz = v[x].size(); i < siz; i++) { int t = v[x][i]; if (t == fa[x]) continue; dep[t] = dep[x] + 1; fa[t] = x; dfs(t); } } inline bool gao() { int p = 0, q = 0; bool flag = true; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return true; for (int hh = p; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i] && dep[i] > dep[q]) q = i; if (q) { reverse(circle.begin(), circle.end()); flag = false; for (int hh = q; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); } else q = fa[circle.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i]) return false; int h1 = p, h2 = q; for (; h1 != h2; h1 = fa[h1]) if (dep[h1] < dep[h2]) swap(h1, h2); rt = h1; if (circle.size() != dep[p] + dep[q] - dep[rt] * 2) return false; vs = p; vt = q; if (flag) reverse(circle.begin(), circle.end()); return true; } int main() { n = rd(); for (int i = 1; i <= n; i++) if (!(a[i] = rd())) h1 = i; for (int i = 1; i <= n; i++) if (!(b[i] = rd())) h2 = i; for (int i = 1; i < n; i++) { int x = rd(), y = rd(); v[x].push_back(y); v[y].push_back(x); } dep[0] = -1; dfs(h2); for (int hh = h1; hh != h2; hh = fa[hh]) swap(a[hh], a[fa[hh]]); long long ans = dep[h1]; if (!gao()) { puts("-1"); return 0; } if (!circle.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, siz = circle.size(); for (int i = 0; i < siz; i++) if (b[circle[i]] == a[circle[0]]) gap = i; for (int i = 0; i < siz; i++) if (b[circle[(i + gap) % siz]] != a[circle[i]]) { puts("-1"); return 0; } for (int i = h1; i; i = fa[i]) vis[i] = true; if (vis[circle[0]] || vis[circle.back()]) { int now = siz; for (int i = 0; i < siz; i++) if (!vis[circle[i]]) { now = i; break; } ans = ans - now + min((long long)gap * (siz + 1) + now, abs((long long)(siz - gap) * (siz + 1) - now)); } else ans = (ans + (long long)min(gap, siz - gap) * (siz + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (vs > vt) swap(vs, vt); printf("%d %d %I64d\n", vs, vt, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; long long ln, lk, lm; int a[200105], b[200105], pa[200105], pb[200105], ta[200105], Cnt, deg[200105]; vector<int> mp[200105], Q; void et() { puts("-1"); exit(0); } bool isC[200105]; int fa[200105]; void dfs(int x, int pa) { fa[x] = pa; deg[x] = deg[pa] + 1; for (int c : mp[x]) if (c != pa) dfs(c, x); } int x, X, y, Y; void fmain() { scanf("%d", &n); for (int(i) = 1; (i) <= (int)(n); (i)++) scanf("%d", a + i); for (int(i) = 1; (i) <= (int)(n); (i)++) scanf("%d", b + i); for (int(i) = 1; (i) <= (int)(n); (i)++) { pa[a[i]] = i; pb[b[i]] = i; ta[i] = a[i]; } for (int i = 0, u, v; i < n - 1; i++) { scanf("%d%d", &u, &v); mp[u].push_back(v); mp[v].push_back(u); } dfs(pb[0], 0); int ans = deg[pa[0]] - 1; for (int s = pa[0]; fa[s] != 0; s = fa[s]) { swap(ta[s], ta[fa[s]]); } for (int(i) = 1; (i) <= (int)(n); (i)++) if (ta[i] != b[i] && deg[i] > deg[x]) x = i; X = x; if (X == 0) { printf("0 %d\n", ans); return; } for (; ta[x] != b[x]; x = fa[x]) { isC[x] = 1; Q.push_back(x); } reverse(Q.begin(), Q.end()); for (int(i) = 1; (i) <= (int)(n); (i)++) if (ta[i] != b[i] && !isC[i] && deg[i] > deg[y]) y = i; Y = y == 0 ? x : y; for (; ta[y] != b[y]; y = fa[y]) { isC[y] = 1; Q.push_back(y); } if (y && y != x) et(); for (int(i) = 1; (i) <= (int)(n); (i)++) if (ta[i] != b[i] && !isC[i]) et(); memset(isC, 0, sizeof isC); for (int i = pa[0]; i; i = fa[i]) isC[i] = 1; if (!Q.empty() && !isC[Q[0]]) reverse(Q.begin(), Q.end()); int p = 0, L = 0; for (int(i) = 0; (i) < (int)(Q.size()); (i)++) if (ta[Q[0]] == b[Q[i]]) { p = i; break; } for (int(i) = 0; (i) < (int)(Q.size()); (i)++) if (ta[Q[i]] != b[Q[(i + p) % Q.size()]]) et(); for (int(i) = 0; (i) < (int)(Q.size()); (i)++) if (!isC[Q[i]]) { L = i; break; } ans += min((Q.size() + 1) * p, (Q.size() + 1) * (Q.size() - p) - 2 * L); for (; !isC[x]; x = fa[x]) ans += 2; if (X > Y) swap(X, Y); printf("%d %d %d\n", X, Y, ans); } int main() { fmain(); return 0; }
### Prompt Please create a solution in cpp to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; long long ln, lk, lm; int a[200105], b[200105], pa[200105], pb[200105], ta[200105], Cnt, deg[200105]; vector<int> mp[200105], Q; void et() { puts("-1"); exit(0); } bool isC[200105]; int fa[200105]; void dfs(int x, int pa) { fa[x] = pa; deg[x] = deg[pa] + 1; for (int c : mp[x]) if (c != pa) dfs(c, x); } int x, X, y, Y; void fmain() { scanf("%d", &n); for (int(i) = 1; (i) <= (int)(n); (i)++) scanf("%d", a + i); for (int(i) = 1; (i) <= (int)(n); (i)++) scanf("%d", b + i); for (int(i) = 1; (i) <= (int)(n); (i)++) { pa[a[i]] = i; pb[b[i]] = i; ta[i] = a[i]; } for (int i = 0, u, v; i < n - 1; i++) { scanf("%d%d", &u, &v); mp[u].push_back(v); mp[v].push_back(u); } dfs(pb[0], 0); int ans = deg[pa[0]] - 1; for (int s = pa[0]; fa[s] != 0; s = fa[s]) { swap(ta[s], ta[fa[s]]); } for (int(i) = 1; (i) <= (int)(n); (i)++) if (ta[i] != b[i] && deg[i] > deg[x]) x = i; X = x; if (X == 0) { printf("0 %d\n", ans); return; } for (; ta[x] != b[x]; x = fa[x]) { isC[x] = 1; Q.push_back(x); } reverse(Q.begin(), Q.end()); for (int(i) = 1; (i) <= (int)(n); (i)++) if (ta[i] != b[i] && !isC[i] && deg[i] > deg[y]) y = i; Y = y == 0 ? x : y; for (; ta[y] != b[y]; y = fa[y]) { isC[y] = 1; Q.push_back(y); } if (y && y != x) et(); for (int(i) = 1; (i) <= (int)(n); (i)++) if (ta[i] != b[i] && !isC[i]) et(); memset(isC, 0, sizeof isC); for (int i = pa[0]; i; i = fa[i]) isC[i] = 1; if (!Q.empty() && !isC[Q[0]]) reverse(Q.begin(), Q.end()); int p = 0, L = 0; for (int(i) = 0; (i) < (int)(Q.size()); (i)++) if (ta[Q[0]] == b[Q[i]]) { p = i; break; } for (int(i) = 0; (i) < (int)(Q.size()); (i)++) if (ta[Q[i]] != b[Q[(i + p) % Q.size()]]) et(); for (int(i) = 0; (i) < (int)(Q.size()); (i)++) if (!isC[Q[i]]) { L = i; break; } ans += min((Q.size() + 1) * p, (Q.size() + 1) * (Q.size() - p) - 2 * L); for (; !isC[x]; x = fa[x]) ans += 2; if (X > Y) swap(X, Y); printf("%d %d %d\n", X, Y, ans); } int main() { fmain(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> lk[maxn]; int fa[maxn], dep[maxn], a[maxn], b[maxn], n; void dfs(int now, int pre) { fa[now] = pre; dep[now] = dep[pre] + 1; for (auto p : lk[now]) if (p != pre) dfs(p, now); } vector<int> cir; int rt, lp, lq; bool find_circle() { cir.clear(); static bool vis[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; int u, v; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[rt]) return 0; lp = p, lq = q; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); lk[u].push_back(v), lk[v].push_back(u); } int pa = find(a + 1, a + n + 1, 0) - a, pb = find(b + 1, b + n + 1, 0) - b; dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; for (int i = 1; i < len; i++) if (b[cir[(i + gap) % len]] != a[cir[i]]) { printf("-1\n"); return 0; } static bool vis[maxn]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; }
### Prompt Construct a CPP code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> lk[maxn]; int fa[maxn], dep[maxn], a[maxn], b[maxn], n; void dfs(int now, int pre) { fa[now] = pre; dep[now] = dep[pre] + 1; for (auto p : lk[now]) if (p != pre) dfs(p, now); } vector<int> cir; int rt, lp, lq; bool find_circle() { cir.clear(); static bool vis[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; int u, v; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[rt]) return 0; lp = p, lq = q; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); lk[u].push_back(v), lk[v].push_back(u); } int pa = find(a + 1, a + n + 1, 0) - a, pb = find(b + 1, b + n + 1, 0) - b; dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; for (int i = 1; i < len; i++) if (b[cir[(i + gap) % len]] != a[cir[i]]) { printf("-1\n"); return 0; } static bool vis[maxn]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 200000; const int MAXM = MAXN - 1; typedef struct E { int u, v; } E; bool operator<(const E &a, const E &b) { if (a.u != b.u) return a.u < b.u; return a.v < b.v; } int n; int oa[MAXN], ob[MAXN]; int a[MAXN], ra[MAXN]; int b[MAXN], rb[MAXN]; bool been[MAXN]; bool d[MAXN]; E e[MAXM]; int adj[MAXN][2], nadj[MAXN]; int p[2][MAXN], np[2], nnp; bool onp[MAXN]; int c[MAXN], rc[MAXN], nc; int head[MAXN], nxt[2 * MAXM], to[2 * MAXM]; int t[MAXN]; bool exists(int u, int v) { if (u > v) swap(u, v); int l = 0, h = n - 1; while (l <= h) { int m = l + (h - l) / 2; if (e[m].u == u && e[m].v == v) return true; if (e[m].u < u || e[m].u == u && e[m].v < v) l = m + 1; else h = m - 1; } return false; } int dfs(int at, int par) { if (been[at]) return 0; int ret = INT_MAX; for (int x = head[at]; x != -1; x = nxt[x]) { if (onp[to[x]] || to[x] == par) continue; int cur = dfs(to[x], at); if (cur == INT_MAX) continue; if (cur + 1 < ret) ret = cur + 1; } return ret; } void run() { scanf("%d", &n); for (int i = (0); i < (n); ++i) scanf("%d", &a[i]); for (int i = (0); i < (n); ++i) ra[a[i]] = i; for (int i = (0); i < (n); ++i) scanf("%d", &b[i]); for (int i = (0); i < (n); ++i) rb[b[i]] = i; for (int i = (0); i < (n - 1); ++i) { scanf("%d%d", &e[i].u, &e[i].v); --e[i].u, --e[i].v; if (e[i].u > e[i].v) swap(e[i].u, e[i].v); } sort(e, e + n - 1); for (int i = (0); i < (n); ++i) been[i] = false, head[i] = -1, oa[i] = a[i], ob[i] = b[i]; for (int i = (0); i < (n - 1); ++i) { int u = e[i].u, v = e[i].v; nxt[2 * i + 0] = head[u]; head[u] = 2 * i + 0; to[2 * i + 0] = v; nxt[2 * i + 1] = head[v]; head[v] = 2 * i + 1; to[2 * i + 1] = u; } int ret = 0; while (true) { int u = ra[0], v = ra[b[u]]; been[u] = true; if (!exists(u, v)) break; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ret; } while (true) { int u = rb[0], v = rb[a[u]]; if (!exists(u, v)) break; swap(b[u], b[v]); swap(rb[b[u]], rb[b[v]]); ++ret; } for (int i = (0); i < (n); ++i) d[i] = a[i] != b[i], nadj[i] = 0, onp[i] = false; nnp = 0; for (int i = (0); i < (n - 1); ++i) if (d[e[i].u] && d[e[i].v]) { int u = e[i].u, v = e[i].v; if (nadj[u] == 2) { printf("-1\n"); return; } else adj[u][nadj[u]++] = v; if (nadj[v] == 2) { printf("-1\n"); return; } else adj[v][nadj[v]++] = u; } for (int i = (0); i < (n); ++i) if (d[i] && nadj[i] <= 1 && !onp[i]) { if (nnp == 2) { printf("-1\n"); return; } else np[nnp] = 0; for (int at = i, to = -1; at != -1; at = to, to = -1) { p[nnp][np[nnp]++] = at; onp[at] = true; for (int j = (0); j < (nadj[at]); ++j) if (!onp[adj[at][j]]) to = adj[at][j]; } ++nnp; } if (nnp == 0) { printf("0 %d\n", ret); return; } if (nnp == 2) for (int i = (0); i < (n); ++i) if (!onp[i] && (exists(i, p[0][0]) || exists(i, p[0][np[0] - 1])) && (exists(i, p[1][0]) || exists(i, p[1][np[1] - 1]))) { if (!exists(i, p[0][np[0] - 1])) reverse(p[0], p[0] + np[0]); if (!exists(i, p[1][0])) reverse(p[1], p[1] + np[1]); p[0][np[0]++] = i; onp[i] = true; for (int j = (0); j < (np[1]); ++j) p[0][np[0]++] = p[1][j]; nnp = 1; break; } if (nnp == 2) { if (np[0] == 1 && np[1] == 1) { printf("%d %d %d\n", min(p[0][0], p[1][0]) + 1, max(p[0][0], p[1][0]) + 1, ret + 1); return; } printf("-1\n"); return; } nc = np[0]; for (int i = (0); i < (nc); ++i) c[i] = p[0][i]; memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; int ccwret = 0, fixidx = -1; if (onp[ra[0]] && onp[rb[0]]) { int idx = rc[ra[0]]; assert(idx != -1); while (ra[0] != rb[0]) { int nidx = idx == nc - 1 ? 0 : idx + 1, u = c[idx], v = c[nidx]; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ccwret; idx = nidx; } fixidx = idx; } else { int dst = INT_MAX; for (int i = (0); i < (nc); ++i) if (been[c[i]] && a[c[i]] == b[c[i]]) dst = 0, fixidx = i; for (int i = (0); i < (nc); ++i) for (int x = head[c[i]]; dst == INT_MAX && x != -1; x = nxt[x]) if (!onp[to[x]]) { int cur = dfs(to[x], i); if (cur == INT_MAX) continue; if (a[c[i]] == b[c[i]]) { dst = cur + 1, fixidx = i; } if (a[c[i]] != b[c[i]]) { if (i != 0 && i != nc - 1) { printf("-1\n"); return; } if (i == 0) reverse(c, c + nc); c[nc++] = to[x]; dst = cur, fixidx = nc - 1; } } assert(dst != INT_MAX); ret += 2 * dst; } memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; if (a[c[fixidx]] != b[c[fixidx]]) { printf("-1\n"); return; } t[fixidx] = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) { int to = rc[rb[a[c[i]]]]; if (to == -1) { printf("-1\n"); return; } if (to < i) to += nc; t[i] = to - i; if (to > fixidx && i < fixidx || i > fixidx && to > nc + fixidx) --t[i]; } int tall = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) if (tall == -1) tall = t[i]; else if (t[i] != tall) { printf("-1\n"); return; } long long ret1 = ret + ccwret + (long long)nc * (nc - 1 - tall); long long ret2 = ret + nc - ccwret + (long long)nc * (tall - 1); printf("%d %d %I64d\n", min(c[0], c[nc - 1]) + 1, max(c[0], c[nc - 1]) + 1, min(ret1, ret2)); } int main() { run(); return 0; }
### Prompt Your task is to create a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 200000; const int MAXM = MAXN - 1; typedef struct E { int u, v; } E; bool operator<(const E &a, const E &b) { if (a.u != b.u) return a.u < b.u; return a.v < b.v; } int n; int oa[MAXN], ob[MAXN]; int a[MAXN], ra[MAXN]; int b[MAXN], rb[MAXN]; bool been[MAXN]; bool d[MAXN]; E e[MAXM]; int adj[MAXN][2], nadj[MAXN]; int p[2][MAXN], np[2], nnp; bool onp[MAXN]; int c[MAXN], rc[MAXN], nc; int head[MAXN], nxt[2 * MAXM], to[2 * MAXM]; int t[MAXN]; bool exists(int u, int v) { if (u > v) swap(u, v); int l = 0, h = n - 1; while (l <= h) { int m = l + (h - l) / 2; if (e[m].u == u && e[m].v == v) return true; if (e[m].u < u || e[m].u == u && e[m].v < v) l = m + 1; else h = m - 1; } return false; } int dfs(int at, int par) { if (been[at]) return 0; int ret = INT_MAX; for (int x = head[at]; x != -1; x = nxt[x]) { if (onp[to[x]] || to[x] == par) continue; int cur = dfs(to[x], at); if (cur == INT_MAX) continue; if (cur + 1 < ret) ret = cur + 1; } return ret; } void run() { scanf("%d", &n); for (int i = (0); i < (n); ++i) scanf("%d", &a[i]); for (int i = (0); i < (n); ++i) ra[a[i]] = i; for (int i = (0); i < (n); ++i) scanf("%d", &b[i]); for (int i = (0); i < (n); ++i) rb[b[i]] = i; for (int i = (0); i < (n - 1); ++i) { scanf("%d%d", &e[i].u, &e[i].v); --e[i].u, --e[i].v; if (e[i].u > e[i].v) swap(e[i].u, e[i].v); } sort(e, e + n - 1); for (int i = (0); i < (n); ++i) been[i] = false, head[i] = -1, oa[i] = a[i], ob[i] = b[i]; for (int i = (0); i < (n - 1); ++i) { int u = e[i].u, v = e[i].v; nxt[2 * i + 0] = head[u]; head[u] = 2 * i + 0; to[2 * i + 0] = v; nxt[2 * i + 1] = head[v]; head[v] = 2 * i + 1; to[2 * i + 1] = u; } int ret = 0; while (true) { int u = ra[0], v = ra[b[u]]; been[u] = true; if (!exists(u, v)) break; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ret; } while (true) { int u = rb[0], v = rb[a[u]]; if (!exists(u, v)) break; swap(b[u], b[v]); swap(rb[b[u]], rb[b[v]]); ++ret; } for (int i = (0); i < (n); ++i) d[i] = a[i] != b[i], nadj[i] = 0, onp[i] = false; nnp = 0; for (int i = (0); i < (n - 1); ++i) if (d[e[i].u] && d[e[i].v]) { int u = e[i].u, v = e[i].v; if (nadj[u] == 2) { printf("-1\n"); return; } else adj[u][nadj[u]++] = v; if (nadj[v] == 2) { printf("-1\n"); return; } else adj[v][nadj[v]++] = u; } for (int i = (0); i < (n); ++i) if (d[i] && nadj[i] <= 1 && !onp[i]) { if (nnp == 2) { printf("-1\n"); return; } else np[nnp] = 0; for (int at = i, to = -1; at != -1; at = to, to = -1) { p[nnp][np[nnp]++] = at; onp[at] = true; for (int j = (0); j < (nadj[at]); ++j) if (!onp[adj[at][j]]) to = adj[at][j]; } ++nnp; } if (nnp == 0) { printf("0 %d\n", ret); return; } if (nnp == 2) for (int i = (0); i < (n); ++i) if (!onp[i] && (exists(i, p[0][0]) || exists(i, p[0][np[0] - 1])) && (exists(i, p[1][0]) || exists(i, p[1][np[1] - 1]))) { if (!exists(i, p[0][np[0] - 1])) reverse(p[0], p[0] + np[0]); if (!exists(i, p[1][0])) reverse(p[1], p[1] + np[1]); p[0][np[0]++] = i; onp[i] = true; for (int j = (0); j < (np[1]); ++j) p[0][np[0]++] = p[1][j]; nnp = 1; break; } if (nnp == 2) { if (np[0] == 1 && np[1] == 1) { printf("%d %d %d\n", min(p[0][0], p[1][0]) + 1, max(p[0][0], p[1][0]) + 1, ret + 1); return; } printf("-1\n"); return; } nc = np[0]; for (int i = (0); i < (nc); ++i) c[i] = p[0][i]; memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; int ccwret = 0, fixidx = -1; if (onp[ra[0]] && onp[rb[0]]) { int idx = rc[ra[0]]; assert(idx != -1); while (ra[0] != rb[0]) { int nidx = idx == nc - 1 ? 0 : idx + 1, u = c[idx], v = c[nidx]; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ccwret; idx = nidx; } fixidx = idx; } else { int dst = INT_MAX; for (int i = (0); i < (nc); ++i) if (been[c[i]] && a[c[i]] == b[c[i]]) dst = 0, fixidx = i; for (int i = (0); i < (nc); ++i) for (int x = head[c[i]]; dst == INT_MAX && x != -1; x = nxt[x]) if (!onp[to[x]]) { int cur = dfs(to[x], i); if (cur == INT_MAX) continue; if (a[c[i]] == b[c[i]]) { dst = cur + 1, fixidx = i; } if (a[c[i]] != b[c[i]]) { if (i != 0 && i != nc - 1) { printf("-1\n"); return; } if (i == 0) reverse(c, c + nc); c[nc++] = to[x]; dst = cur, fixidx = nc - 1; } } assert(dst != INT_MAX); ret += 2 * dst; } memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; if (a[c[fixidx]] != b[c[fixidx]]) { printf("-1\n"); return; } t[fixidx] = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) { int to = rc[rb[a[c[i]]]]; if (to == -1) { printf("-1\n"); return; } if (to < i) to += nc; t[i] = to - i; if (to > fixidx && i < fixidx || i > fixidx && to > nc + fixidx) --t[i]; } int tall = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) if (tall == -1) tall = t[i]; else if (t[i] != tall) { printf("-1\n"); return; } long long ret1 = ret + ccwret + (long long)nc * (nc - 1 - tall); long long ret2 = ret + nc - ccwret + (long long)nc * (tall - 1); printf("%d %d %I64d\n", min(c[0], c[nc - 1]) + 1, max(c[0], c[nc - 1]) + 1, min(ret1, ret2)); } int main() { run(); return 0; } ```
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { x = (x << 3) + (x << 1) + (c ^ 48); c = getchar(); } return f == 1 ? x : ~x + 1; } void Fail() { printf("-1\n"); exit(0); } long long n; long long a[200010], b[200010]; long long dep[200010]; vector<long long> vec[200010]; long long s, t; vector<long long> to; bool dfs(long long x, long long fa) { to.push_back(x); if (x == t) { return 1; } for (long long v : vec[x]) { if (v != fa && dfs(v, x)) return 1; } to.pop_back(); return 0; } bool vis[200010]; long long deg[200010]; long long up = -1; vector<long long> A, B; vector<long long> cir; void getcircle(long long x, long long fa) { dep[x] = dep[fa] + 1; if (a[x] != b[x]) { if (up == -1 || dep[up] >= dep[x]) up = fa; cir.push_back(x); vis[x] = 1; } for (long long v : vec[x]) { if (v != fa) getcircle(v, x); } } void getseq(long long x, long long fa) { if (x != up) { A.push_back(a[x]); B.push_back(b[x]); } for (long long v : vec[x]) { if (vis[v] && v != fa) getseq(v, x); } } long long calc(vector<long long> A, vector<long long> B) { long long siz = A.size(); long long pos = 0; for (long long i = 0; i < siz; ++i) { if (B[i] == A[0]) { pos = i; break; } } if (pos == 0) return 0; for (long long i = 0; i < siz; ++i) { if (A[i] != B[(i + pos) % siz]) return 0; } return pos; } long long getdis(long long x, long long fa, long long dis, long long y) { if (x == y) return dis; for (long long v : vec[x]) { if (v == fa) continue; long long d = getdis(v, x, dis + 1, y); if (d) return d; } return 0; } long long dis(long long x, long long y) { return getdis(x, 0, 0, y); } long long get(long long u, long long v) { long long c = calc(A, B); return dis(s, u) + (c - 1) * (A.size() + 1) + 1 + dis(v, t); } signed main() { n = read(); for (long long i = 1; i <= n; ++i) a[i] = read(); for (long long i = 1; i <= n; ++i) b[i] = read(); for (long long i = 1; i <= n; ++i) if (a[i] == 0) s = i; for (long long i = 1; i <= n; ++i) if (b[i] == 0) t = i; for (long long i = 1; i < n; ++i) { long long u = read(), v = read(); vec[u].push_back(v), vec[v].push_back(u); } dfs(s, 0); for (long long i = 0; i < to.size() - 1; ++i) swap(a[to[i]], a[to[i + 1]]); bool ok = 1; for (long long i = 1; i <= n; ++i) ok = ok & (a[i] == b[i]); if (ok) { printf("0 %d\n", to.size() - 1); return 0; } getcircle(t, 0); vis[up] = 1; cir.push_back(up); vector<long long> u; for (long long x : cir) { for (long long v : vec[x]) { if (vis[v]) ++deg[x]; } if (deg[x] == 1) { u.push_back(x); } else if (deg[x] != 2) { Fail(); } } if (u.size() != 2) { Fail(); } if (u[0] > u[1]) swap(u[0], u[1]); getseq(u[0], 0); if (!calc(A, B)) { Fail(); } printf("%d %d ", u[0], u[1]); long long ans = get(u[0], u[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); printf("%lld\n", min(ans, get(u[1], u[0]))); }
### Prompt Please formulate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { x = (x << 3) + (x << 1) + (c ^ 48); c = getchar(); } return f == 1 ? x : ~x + 1; } void Fail() { printf("-1\n"); exit(0); } long long n; long long a[200010], b[200010]; long long dep[200010]; vector<long long> vec[200010]; long long s, t; vector<long long> to; bool dfs(long long x, long long fa) { to.push_back(x); if (x == t) { return 1; } for (long long v : vec[x]) { if (v != fa && dfs(v, x)) return 1; } to.pop_back(); return 0; } bool vis[200010]; long long deg[200010]; long long up = -1; vector<long long> A, B; vector<long long> cir; void getcircle(long long x, long long fa) { dep[x] = dep[fa] + 1; if (a[x] != b[x]) { if (up == -1 || dep[up] >= dep[x]) up = fa; cir.push_back(x); vis[x] = 1; } for (long long v : vec[x]) { if (v != fa) getcircle(v, x); } } void getseq(long long x, long long fa) { if (x != up) { A.push_back(a[x]); B.push_back(b[x]); } for (long long v : vec[x]) { if (vis[v] && v != fa) getseq(v, x); } } long long calc(vector<long long> A, vector<long long> B) { long long siz = A.size(); long long pos = 0; for (long long i = 0; i < siz; ++i) { if (B[i] == A[0]) { pos = i; break; } } if (pos == 0) return 0; for (long long i = 0; i < siz; ++i) { if (A[i] != B[(i + pos) % siz]) return 0; } return pos; } long long getdis(long long x, long long fa, long long dis, long long y) { if (x == y) return dis; for (long long v : vec[x]) { if (v == fa) continue; long long d = getdis(v, x, dis + 1, y); if (d) return d; } return 0; } long long dis(long long x, long long y) { return getdis(x, 0, 0, y); } long long get(long long u, long long v) { long long c = calc(A, B); return dis(s, u) + (c - 1) * (A.size() + 1) + 1 + dis(v, t); } signed main() { n = read(); for (long long i = 1; i <= n; ++i) a[i] = read(); for (long long i = 1; i <= n; ++i) b[i] = read(); for (long long i = 1; i <= n; ++i) if (a[i] == 0) s = i; for (long long i = 1; i <= n; ++i) if (b[i] == 0) t = i; for (long long i = 1; i < n; ++i) { long long u = read(), v = read(); vec[u].push_back(v), vec[v].push_back(u); } dfs(s, 0); for (long long i = 0; i < to.size() - 1; ++i) swap(a[to[i]], a[to[i + 1]]); bool ok = 1; for (long long i = 1; i <= n; ++i) ok = ok & (a[i] == b[i]); if (ok) { printf("0 %d\n", to.size() - 1); return 0; } getcircle(t, 0); vis[up] = 1; cir.push_back(up); vector<long long> u; for (long long x : cir) { for (long long v : vec[x]) { if (vis[v]) ++deg[x]; } if (deg[x] == 1) { u.push_back(x); } else if (deg[x] != 2) { Fail(); } } if (u.size() != 2) { Fail(); } if (u[0] > u[1]) swap(u[0], u[1]); getseq(u[0], 0); if (!calc(A, B)) { Fail(); } printf("%d %d ", u[0], u[1]); long long ans = get(u[0], u[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); printf("%lld\n", min(ans, get(u[1], u[0]))); } ```
#include <bits/stdc++.h> using namespace std; const long long linf = 1e18 + 7; const int maxn = 2e5 + 7; struct Edge { int nxt, to; } G[maxn << 1]; int n, S, T, target, hG[maxn], bG = 0, a[maxn], b[maxn], dep[maxn], fa[maxn], cnt = 0, num = 0, top = 0; int rk[maxn], val[maxn], val2[maxn], id[maxn], tot = 0, thetop[2], thelst[2], nw[maxn], aa[maxn]; bool vis[maxn], on[maxn], ok = false; long long ans = linf; stack<int> st; inline void add(int x, int y) { G[bG].nxt = hG[x]; G[bG].to = y; hG[x] = bG++; G[bG].nxt = hG[y]; G[bG].to = x; hG[y] = bG++; } void turnit(int v, int p, int d) { dep[v] = d; fa[v] = p; if (v == T) ok = true; for (int i = hG[v]; i != -1; i = G[i].nxt) { int u = G[i].to; if (u == p) continue; if (!ok) swap(a[u], a[v]); turnit(u, v, d + 1); if (!ok) swap(a[u], a[v]); } } void findit(int v, int p, int d) { dep[v] = d; fa[v] = p; for (int i = hG[v]; i != -1; i = G[i].nxt) { int u = G[i].to; if (u == p) continue; findit(u, v, d + 1); } } inline void badend() { puts("-1"); exit(0); } inline bool cmp(int l, int r) { return dep[l] > dep[r]; } void doit(int St, int dis) { long long res = dis; int kk = -1; for (int i = 0; i < cnt; i++) { if (a[id[i]] == b[id[0]]) kk = i; } res += 1ll * min(kk, cnt - kk) * (cnt + 1); res += dep[target]; ans = min(ans, res); } void dfs(int v, int p, int d) { if (v == target) { doit(v, d); return; } for (int i = hG[v]; i != -1; i = G[i].nxt) { int u = G[i].to; if (u == p) continue; swap(a[u], a[v]); dfs(u, v, d + 1); swap(a[u], a[v]); } } int main() { scanf("%d", &n); memset(hG, -1, sizeof(hG)); for (int i = 0; i < n; i++) { scanf("%d", a + i); if (!a[i]) S = i; aa[i] = a[i]; } for (int i = 0; i < n; i++) { scanf("%d", b + i); if (!b[i]) T = i; } for (int i = 0; i < n - 1; i++) { int x, y; scanf("%d%d", &x, &y); x--; y--; add(x, y); } turnit(S, -1, 0); cnt = 0; for (int i = 0; i < n; i++) if (a[i] != b[i]) nw[cnt++] = i; if (!cnt) { printf("0 %d\n", dep[T]); return 0; } findit(T, -1, 0); sort(nw, nw + cnt, cmp); for (int ii = 0; ii < cnt; ii++) { int i = nw[ii]; if (a[i] == b[i] || vis[i]) continue; if (top >= 2) badend(); int t = i, pre; while (a[t] != b[t]) { if (vis[t]) badend(); pre = t; vis[t] = true; num++; if (!top) { rk[t] = tot; id[tot++] = t; } else st.push(t); t = fa[t]; } thetop[top] = pre; thelst[top] = i; if (top) { if (fa[pre] != fa[thetop[0]]) badend(); while (!st.empty()) { rk[st.top()] = tot; id[tot++] = st.top(); st.pop(); } } top++; } if (tot != cnt || cnt != num) badend(); target = fa[thetop[0]]; for (int i = 0; i < cnt; i++) { val[i] = a[id[i]]; val2[i] = b[id[i]]; on[id[i]] = true; } int kk = -1; for (int i = 0; i < cnt; i++) { if (val2[i] == val[0]) kk = i; } if (kk == -1) badend(); for (int i = 0, j = kk; i < cnt; i++, j = (j + 1) % cnt) { if (val[i] != val2[j]) badend(); } int u, v; if (top == 2) { u = thelst[0] + 1; v = thelst[1] + 1; if (u > v) swap(u, v); printf("%d %d ", u, v); add(thelst[0], thelst[1]); } else { u = target + 1, v = thelst[0] + 1; if (u > v) swap(u, v); printf("%d %d ", u, v); add(target, thelst[0]); } for (int i = 0; i < n; i++) a[i] = aa[i]; dfs(S, -1, 0); printf("%lld\n", ans); return 0; }
### Prompt Your task is to create a CPP solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long linf = 1e18 + 7; const int maxn = 2e5 + 7; struct Edge { int nxt, to; } G[maxn << 1]; int n, S, T, target, hG[maxn], bG = 0, a[maxn], b[maxn], dep[maxn], fa[maxn], cnt = 0, num = 0, top = 0; int rk[maxn], val[maxn], val2[maxn], id[maxn], tot = 0, thetop[2], thelst[2], nw[maxn], aa[maxn]; bool vis[maxn], on[maxn], ok = false; long long ans = linf; stack<int> st; inline void add(int x, int y) { G[bG].nxt = hG[x]; G[bG].to = y; hG[x] = bG++; G[bG].nxt = hG[y]; G[bG].to = x; hG[y] = bG++; } void turnit(int v, int p, int d) { dep[v] = d; fa[v] = p; if (v == T) ok = true; for (int i = hG[v]; i != -1; i = G[i].nxt) { int u = G[i].to; if (u == p) continue; if (!ok) swap(a[u], a[v]); turnit(u, v, d + 1); if (!ok) swap(a[u], a[v]); } } void findit(int v, int p, int d) { dep[v] = d; fa[v] = p; for (int i = hG[v]; i != -1; i = G[i].nxt) { int u = G[i].to; if (u == p) continue; findit(u, v, d + 1); } } inline void badend() { puts("-1"); exit(0); } inline bool cmp(int l, int r) { return dep[l] > dep[r]; } void doit(int St, int dis) { long long res = dis; int kk = -1; for (int i = 0; i < cnt; i++) { if (a[id[i]] == b[id[0]]) kk = i; } res += 1ll * min(kk, cnt - kk) * (cnt + 1); res += dep[target]; ans = min(ans, res); } void dfs(int v, int p, int d) { if (v == target) { doit(v, d); return; } for (int i = hG[v]; i != -1; i = G[i].nxt) { int u = G[i].to; if (u == p) continue; swap(a[u], a[v]); dfs(u, v, d + 1); swap(a[u], a[v]); } } int main() { scanf("%d", &n); memset(hG, -1, sizeof(hG)); for (int i = 0; i < n; i++) { scanf("%d", a + i); if (!a[i]) S = i; aa[i] = a[i]; } for (int i = 0; i < n; i++) { scanf("%d", b + i); if (!b[i]) T = i; } for (int i = 0; i < n - 1; i++) { int x, y; scanf("%d%d", &x, &y); x--; y--; add(x, y); } turnit(S, -1, 0); cnt = 0; for (int i = 0; i < n; i++) if (a[i] != b[i]) nw[cnt++] = i; if (!cnt) { printf("0 %d\n", dep[T]); return 0; } findit(T, -1, 0); sort(nw, nw + cnt, cmp); for (int ii = 0; ii < cnt; ii++) { int i = nw[ii]; if (a[i] == b[i] || vis[i]) continue; if (top >= 2) badend(); int t = i, pre; while (a[t] != b[t]) { if (vis[t]) badend(); pre = t; vis[t] = true; num++; if (!top) { rk[t] = tot; id[tot++] = t; } else st.push(t); t = fa[t]; } thetop[top] = pre; thelst[top] = i; if (top) { if (fa[pre] != fa[thetop[0]]) badend(); while (!st.empty()) { rk[st.top()] = tot; id[tot++] = st.top(); st.pop(); } } top++; } if (tot != cnt || cnt != num) badend(); target = fa[thetop[0]]; for (int i = 0; i < cnt; i++) { val[i] = a[id[i]]; val2[i] = b[id[i]]; on[id[i]] = true; } int kk = -1; for (int i = 0; i < cnt; i++) { if (val2[i] == val[0]) kk = i; } if (kk == -1) badend(); for (int i = 0, j = kk; i < cnt; i++, j = (j + 1) % cnt) { if (val[i] != val2[j]) badend(); } int u, v; if (top == 2) { u = thelst[0] + 1; v = thelst[1] + 1; if (u > v) swap(u, v); printf("%d %d ", u, v); add(thelst[0], thelst[1]); } else { u = target + 1, v = thelst[0] + 1; if (u > v) swap(u, v); printf("%d %d ", u, v); add(target, thelst[0]); } for (int i = 0; i < n; i++) a[i] = aa[i]; dfs(S, -1, 0); printf("%lld\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; void gg() { printf("-1\n"); exit(0); return; } int n; struct Edge { int v, nxt; } e[400010]; int tot; int first[200010]; void build(int u, int v) { e[++tot] = (Edge){v, first[u]}; first[u] = tot; return; } int a[200010], b[200010]; int fa[200010]; int dis[200010]; int pos[200010]; void dfs1(int u, int lst) { fa[u] = lst; if (lst) dis[u] = dis[lst] + 1; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != lst) dfs1(e[i].v, u); return; } bool vis[200010]; void work1() { int x = pos[1]; int res = dis[x]; while (x != 1) { vis[x] = true; swap(b[x], b[fa[x]]); x = fa[x]; } vis[1] = true; for (int i = 1; i <= n; i++) if (b[i] != i) return; printf("0 %d\n", res); exit(0); } vector<int> vec[2]; int num = 0; void getpath(int u) { if (num == 2 || (num == 1 && fa[u] != fa[vec[0][0]])) gg(); while (u) { vec[num].push_back(u); int v = 0; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u] && b[e[i].v] != e[i].v) { if (!v) v = e[i].v; else gg(); } u = v; } num++; } void dfs2(int u) { for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u]) { if (b[e[i].v] == e[i].v) dfs2(e[i].v); else getpath(e[i].v); } return; } int tmp[200010]; int ori[200010]; void work2() { int u, v, x; if (num == 1) { x = u = fa[vec[0][0]]; v = vec[0][vec[0].size() - 1]; } else { x = fa[vec[0][0]]; u = vec[0][vec[0].size() - 1]; v = vec[1][vec[1].size() - 1]; for (int i = 1; i <= vec[1].size(); i++) vec[0].push_back(vec[1][vec[1].size() - i]); } memset(tmp, -1, sizeof(tmp)); int k = 0, num = vec[0].size(); for (int i = 0; i < num; i++) { int o = vec[0][i]; tmp[o] = i; } for (int i = 1; i <= n; i++) if (tmp[i] == -1 && b[i] != i) gg(); for (int i = 0; i < num; i++) { int o = vec[0][i]; int val = (tmp[b[o]] + num - i) % num; if (i == 0) k = val; else if (k != val) gg(); } int dist = dis[u] + dis[v] - dis[x] * 2 + 1; long long ans; if (!vis[x]) { k = min(k, num - k); ans = (long long)k * dist; while (!vis[x]) ans += 2, x = fa[x]; ans += dis[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { int o = vec[0][i]; cnt += vis[o]; } if (vis[vec[0][0]]) ans = min((long long)dist * k, (long long)dist * (num - k) - 2 * cnt) + dis[pos[1]]; else ans = min((long long)dist * k - 2 * cnt, (long long)dist * (num - k)) + dis[pos[1]]; } u = ori[u]; v = ori[v]; if (u > v) swap(u, v); printf("%d %d %I64d\n", u, v, ans); return; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); u = a[u]; v = a[v]; build(u, v); build(v, u); } dfs1(1, 0); work1(); dfs2(1); work2(); return 0; }
### Prompt Develop a solution in cpp to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void gg() { printf("-1\n"); exit(0); return; } int n; struct Edge { int v, nxt; } e[400010]; int tot; int first[200010]; void build(int u, int v) { e[++tot] = (Edge){v, first[u]}; first[u] = tot; return; } int a[200010], b[200010]; int fa[200010]; int dis[200010]; int pos[200010]; void dfs1(int u, int lst) { fa[u] = lst; if (lst) dis[u] = dis[lst] + 1; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != lst) dfs1(e[i].v, u); return; } bool vis[200010]; void work1() { int x = pos[1]; int res = dis[x]; while (x != 1) { vis[x] = true; swap(b[x], b[fa[x]]); x = fa[x]; } vis[1] = true; for (int i = 1; i <= n; i++) if (b[i] != i) return; printf("0 %d\n", res); exit(0); } vector<int> vec[2]; int num = 0; void getpath(int u) { if (num == 2 || (num == 1 && fa[u] != fa[vec[0][0]])) gg(); while (u) { vec[num].push_back(u); int v = 0; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u] && b[e[i].v] != e[i].v) { if (!v) v = e[i].v; else gg(); } u = v; } num++; } void dfs2(int u) { for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u]) { if (b[e[i].v] == e[i].v) dfs2(e[i].v); else getpath(e[i].v); } return; } int tmp[200010]; int ori[200010]; void work2() { int u, v, x; if (num == 1) { x = u = fa[vec[0][0]]; v = vec[0][vec[0].size() - 1]; } else { x = fa[vec[0][0]]; u = vec[0][vec[0].size() - 1]; v = vec[1][vec[1].size() - 1]; for (int i = 1; i <= vec[1].size(); i++) vec[0].push_back(vec[1][vec[1].size() - i]); } memset(tmp, -1, sizeof(tmp)); int k = 0, num = vec[0].size(); for (int i = 0; i < num; i++) { int o = vec[0][i]; tmp[o] = i; } for (int i = 1; i <= n; i++) if (tmp[i] == -1 && b[i] != i) gg(); for (int i = 0; i < num; i++) { int o = vec[0][i]; int val = (tmp[b[o]] + num - i) % num; if (i == 0) k = val; else if (k != val) gg(); } int dist = dis[u] + dis[v] - dis[x] * 2 + 1; long long ans; if (!vis[x]) { k = min(k, num - k); ans = (long long)k * dist; while (!vis[x]) ans += 2, x = fa[x]; ans += dis[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { int o = vec[0][i]; cnt += vis[o]; } if (vis[vec[0][0]]) ans = min((long long)dist * k, (long long)dist * (num - k) - 2 * cnt) + dis[pos[1]]; else ans = min((long long)dist * k - 2 * cnt, (long long)dist * (num - k)) + dis[pos[1]]; } u = ori[u]; v = ori[v]; if (u > v) swap(u, v); printf("%d %d %I64d\n", u, v, ans); return; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); u = a[u]; v = a[v]; build(u, v); build(v, u); } dfs1(1, 0); work1(); dfs2(1); work2(); return 0; } ```
#include <bits/stdc++.h> using namespace std; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } const int oo = 0x3f3f3f3f; const int maxn = 200000; struct edge { int id, nxt; edge() {} edge(int _id, int _nxt) : id(_id), nxt(_nxt) {} }; edge e[(maxn << 1) + 5]; int st[maxn + 5], en = 0; inline void add_edge(int first, int second) { e[en] = edge(second, st[first]), st[first] = en++; } int n; int dep[maxn + 5], fa[maxn + 5]; int dfs_tot = 0; int dfn[maxn + 5], End[maxn + 5]; void dfs(int first, int f = -1) { if (~f) dep[first] = dep[f] + 1; else dep[first] = 0; dfn[first] = dfs_tot++; fa[first] = f; for (int i = st[first]; i != -1; i = e[i].nxt) { int second = e[i].id; if (second == f) continue; dfs(second, first); } End[first] = dfs_tot; } int pa, push_back; int a[maxn + 5], b[maxn + 5]; int main() { memset(st, -1, sizeof st), en = 0; scanf("%d", &n); for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", a + i); pa = find(a, a + n, 0) - a; for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", b + i); push_back = find(b, b + n, 0) - b; for (int i = (0), _end_ = (n - 1); i < _end_; ++i) { int first, second; scanf("%d%d", &first, &second), --first, --second; add_edge(first, second), add_edge(second, first); } dfs(push_back); int u = pa; while (u != push_back) { a[u] = a[fa[u]]; u = fa[u]; } a[u] = 0; int first = -1, rt = -1; int cnt = 0; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i]) { ++cnt; if (!~rt || dep[i] < dep[rt]) rt = i; if (!~first || dep[i] > dep[first]) first = i; } if (!cnt) printf("0 %d\n", dep[pa]), exit(0); assert(first != -1 && rt != -1); if (!~fa[rt]) printf("-1\n"), exit(0); rt = fa[rt]; int second = rt; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i] && (End[i] <= dfn[first] || dfn[i] > dfn[first]) && dep[i] > dep[second]) second = i; if (dep[first] + dep[second] - (dep[rt] << 1) != cnt) printf("-1\n"), exit(0); vector<int> all; int id = first; while (id != rt) { all.push_back(id); id = fa[id]; } reverse((all).begin(), (all).end()); id = second; while (id != rt) { all.push_back(id); id = fa[id]; } int go = -1; for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[0]] == b[all[i]]) { go = i; break; } if (!~go) printf("-1\n"), exit(0); for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[i]] != b[all[(i + go) % (int((all).size()))]]) printf("-1\n"), exit(0); long long ans = dep[pa]; static bool vis[maxn + 5]; memset(vis, 0, sizeof vis); id = pa; while (~id) { vis[id] = 1; id = fa[id]; } if (vis[all[0]] || vis[all.back()]) { if (vis[all.back()]) reverse((all).begin(), (all).end()), go = (int((all).size())) - go; int tmp = (int((all).size())); for (int i = (1), _end_ = ((int((all).size()))); i < _end_; ++i) if (!vis[all[i]]) { tmp = i; break; } int cyc_len = (int((all).size())) + 1; ans -= tmp; ans += min(abs(tmp + (long long)go * cyc_len), abs(tmp + (long long)(go - (int((all).size()))) * cyc_len)); } else ans += min(go, (int((all).size())) - go) * (cnt + 1); id = rt; while (!vis[id]) { ans += 2; id = fa[id]; } if (first > second) swap(first, second); printf("%d %d %I64d\n", first + 1, second + 1, ans); return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } const int oo = 0x3f3f3f3f; const int maxn = 200000; struct edge { int id, nxt; edge() {} edge(int _id, int _nxt) : id(_id), nxt(_nxt) {} }; edge e[(maxn << 1) + 5]; int st[maxn + 5], en = 0; inline void add_edge(int first, int second) { e[en] = edge(second, st[first]), st[first] = en++; } int n; int dep[maxn + 5], fa[maxn + 5]; int dfs_tot = 0; int dfn[maxn + 5], End[maxn + 5]; void dfs(int first, int f = -1) { if (~f) dep[first] = dep[f] + 1; else dep[first] = 0; dfn[first] = dfs_tot++; fa[first] = f; for (int i = st[first]; i != -1; i = e[i].nxt) { int second = e[i].id; if (second == f) continue; dfs(second, first); } End[first] = dfs_tot; } int pa, push_back; int a[maxn + 5], b[maxn + 5]; int main() { memset(st, -1, sizeof st), en = 0; scanf("%d", &n); for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", a + i); pa = find(a, a + n, 0) - a; for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", b + i); push_back = find(b, b + n, 0) - b; for (int i = (0), _end_ = (n - 1); i < _end_; ++i) { int first, second; scanf("%d%d", &first, &second), --first, --second; add_edge(first, second), add_edge(second, first); } dfs(push_back); int u = pa; while (u != push_back) { a[u] = a[fa[u]]; u = fa[u]; } a[u] = 0; int first = -1, rt = -1; int cnt = 0; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i]) { ++cnt; if (!~rt || dep[i] < dep[rt]) rt = i; if (!~first || dep[i] > dep[first]) first = i; } if (!cnt) printf("0 %d\n", dep[pa]), exit(0); assert(first != -1 && rt != -1); if (!~fa[rt]) printf("-1\n"), exit(0); rt = fa[rt]; int second = rt; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i] && (End[i] <= dfn[first] || dfn[i] > dfn[first]) && dep[i] > dep[second]) second = i; if (dep[first] + dep[second] - (dep[rt] << 1) != cnt) printf("-1\n"), exit(0); vector<int> all; int id = first; while (id != rt) { all.push_back(id); id = fa[id]; } reverse((all).begin(), (all).end()); id = second; while (id != rt) { all.push_back(id); id = fa[id]; } int go = -1; for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[0]] == b[all[i]]) { go = i; break; } if (!~go) printf("-1\n"), exit(0); for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[i]] != b[all[(i + go) % (int((all).size()))]]) printf("-1\n"), exit(0); long long ans = dep[pa]; static bool vis[maxn + 5]; memset(vis, 0, sizeof vis); id = pa; while (~id) { vis[id] = 1; id = fa[id]; } if (vis[all[0]] || vis[all.back()]) { if (vis[all.back()]) reverse((all).begin(), (all).end()), go = (int((all).size())) - go; int tmp = (int((all).size())); for (int i = (1), _end_ = ((int((all).size()))); i < _end_; ++i) if (!vis[all[i]]) { tmp = i; break; } int cyc_len = (int((all).size())) + 1; ans -= tmp; ans += min(abs(tmp + (long long)go * cyc_len), abs(tmp + (long long)(go - (int((all).size()))) * cyc_len)); } else ans += min(go, (int((all).size())) - go) * (cnt + 1); id = rt; while (!vis[id]) { ans += 2; id = fa[id]; } if (first > second) swap(first, second); printf("%d %d %I64d\n", first + 1, second + 1, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f = ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 200005; int n, s0, t0, s, t, tp; vector<int> e[N], ch[N]; int a[N], b[N], c[N], f[N]; deque<int> id; int find(int *a, int v) { for (int i = (1); i <= (n); i++) if (a[i] == v) return i; return 0; } int check(int *a, int *b) { for (int i = (1); i <= (n); i++) if (a[i] != b[i]) return 0; return 1; } int fa[N], dep[N], anc[N][20]; void dfs(int x, int pre = 0, int d = 0) { anc[x][0] = fa[x] = pre, dep[x] = d; for (int i = (1); i <= (19); i++) anc[x][i] = anc[anc[x][i - 1]][i - 1]; for (auto y : e[x]) if (y != pre) dfs(y, x, d + 1); } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = (19); i >= (0); i--) if (dep[x] - (1 << i) >= dep[y]) x = anc[x][i]; if (x == y) return x; for (int i = (19); i >= (0); i--) if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i]; return fa[x]; } int dis(int x, int y) { return dep[x] + dep[y] - 2 * dep[LCA(x, y)]; } void getc() { s0 = find(a, 0), t0 = find(b, 0); dfs(t0); for (int i = (1); i <= (n); i++) c[i] = a[i]; for (int x = s0; x != t0; x = fa[x]) id.push_back(x), swap(c[x], c[fa[x]]); id.push_back(t0); if (check(b, c)) printf("0 %d\n", dep[s0]), exit(0); } void NO() { puts("-1"); exit(0); } vector<int> cid; void dfs_ch(int x, int pre = 0) { cid.push_back(x); if (x == t) tp = (int)cid.size() - 1; for (auto y : ch[x]) if (y != pre) dfs_ch(y, x); } int main() { n = read(); for (int i = (1); i <= (n); i++) a[i] = read(); int Test = a[1] == 3779; for (int i = (1); i <= (n); i++) b[i] = read(); for (int i = (1); i <= (n - 1); i++) { int x = read(), y = read(); e[x].push_back(y), e[y].push_back(x); } getc(); deque<int> ID = id; while ((int)id.size() >= 2 && b[id[0]] == c[id[0]]) id.pop_front(); while ((int)id.size() >= 2 && b[id[(int)id.size() - 2]] == c[id[(int)id.size() - 2]]) id.pop_back(); assert(!id.empty()); s = id.front(), t = id.back(); if (b[id[0]] != c[id[0]]) { for (auto i : id) f[i] = 1; } else { int x = -1; for (int i = (1); i <= (n); i++) if (b[i] != c[i]) if (x == -1 || dis(i, t0) < dis(x, t0)) x = i; assert(x != -1); for (auto y : e[x]) if (dis(y, t0) < dis(x, t0)) { f[s = t = y] = 1; break; } assert(s != 0); } for (int i = (1); i <= (n); i++) if (b[i] != c[i]) f[i] = 1; for (int i = (1); i <= (n); i++) for (auto j : e[i]) if (f[i] && f[j]) ch[i].push_back(j); int A = -1, B = -1; for (int i = (1); i <= (n); i++) if (ch[i].size() > 2) NO(); else if (ch[i].size() == 1) { if (A == -1) A = i; else if (B == -1) B = i; else NO(); } else if (ch[i].empty() && f[i]) NO(); if (B == -1) NO(); if (dis(B, s) < dis(B, t)) swap(A, B); b[t] = c[t] = 0; dfs_ch(A); vector<int> pos(n + 1, -1); int cs = (int)cid.size(); for (int i = (0); i <= (cs - 1); i++) pos[b[cid[i]]] = i; int d = -1; for (int i = (0); i <= (cs - 1); i++) { if (cid[i] == t) continue; int p0 = pos[c[cid[i]]], p1 = i; p0 -= p0 >= tp, p1 -= p1 >= tp; int di = (p1 - p0 + cs - 1) % (cs - 1); if (d != -1 && d != di) NO(); d = di; } int dst = dis(s, t); long long d1 = (long long)cs * d + dst, d2 = (long long)cs * (cs - 1) - d1; long long ans = dis(s0, s) + dis(t0, t) + min(d1, d2); cout << min(A, B) << " " << max(A, B) << " " << ans << endl; return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f = ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 200005; int n, s0, t0, s, t, tp; vector<int> e[N], ch[N]; int a[N], b[N], c[N], f[N]; deque<int> id; int find(int *a, int v) { for (int i = (1); i <= (n); i++) if (a[i] == v) return i; return 0; } int check(int *a, int *b) { for (int i = (1); i <= (n); i++) if (a[i] != b[i]) return 0; return 1; } int fa[N], dep[N], anc[N][20]; void dfs(int x, int pre = 0, int d = 0) { anc[x][0] = fa[x] = pre, dep[x] = d; for (int i = (1); i <= (19); i++) anc[x][i] = anc[anc[x][i - 1]][i - 1]; for (auto y : e[x]) if (y != pre) dfs(y, x, d + 1); } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = (19); i >= (0); i--) if (dep[x] - (1 << i) >= dep[y]) x = anc[x][i]; if (x == y) return x; for (int i = (19); i >= (0); i--) if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i]; return fa[x]; } int dis(int x, int y) { return dep[x] + dep[y] - 2 * dep[LCA(x, y)]; } void getc() { s0 = find(a, 0), t0 = find(b, 0); dfs(t0); for (int i = (1); i <= (n); i++) c[i] = a[i]; for (int x = s0; x != t0; x = fa[x]) id.push_back(x), swap(c[x], c[fa[x]]); id.push_back(t0); if (check(b, c)) printf("0 %d\n", dep[s0]), exit(0); } void NO() { puts("-1"); exit(0); } vector<int> cid; void dfs_ch(int x, int pre = 0) { cid.push_back(x); if (x == t) tp = (int)cid.size() - 1; for (auto y : ch[x]) if (y != pre) dfs_ch(y, x); } int main() { n = read(); for (int i = (1); i <= (n); i++) a[i] = read(); int Test = a[1] == 3779; for (int i = (1); i <= (n); i++) b[i] = read(); for (int i = (1); i <= (n - 1); i++) { int x = read(), y = read(); e[x].push_back(y), e[y].push_back(x); } getc(); deque<int> ID = id; while ((int)id.size() >= 2 && b[id[0]] == c[id[0]]) id.pop_front(); while ((int)id.size() >= 2 && b[id[(int)id.size() - 2]] == c[id[(int)id.size() - 2]]) id.pop_back(); assert(!id.empty()); s = id.front(), t = id.back(); if (b[id[0]] != c[id[0]]) { for (auto i : id) f[i] = 1; } else { int x = -1; for (int i = (1); i <= (n); i++) if (b[i] != c[i]) if (x == -1 || dis(i, t0) < dis(x, t0)) x = i; assert(x != -1); for (auto y : e[x]) if (dis(y, t0) < dis(x, t0)) { f[s = t = y] = 1; break; } assert(s != 0); } for (int i = (1); i <= (n); i++) if (b[i] != c[i]) f[i] = 1; for (int i = (1); i <= (n); i++) for (auto j : e[i]) if (f[i] && f[j]) ch[i].push_back(j); int A = -1, B = -1; for (int i = (1); i <= (n); i++) if (ch[i].size() > 2) NO(); else if (ch[i].size() == 1) { if (A == -1) A = i; else if (B == -1) B = i; else NO(); } else if (ch[i].empty() && f[i]) NO(); if (B == -1) NO(); if (dis(B, s) < dis(B, t)) swap(A, B); b[t] = c[t] = 0; dfs_ch(A); vector<int> pos(n + 1, -1); int cs = (int)cid.size(); for (int i = (0); i <= (cs - 1); i++) pos[b[cid[i]]] = i; int d = -1; for (int i = (0); i <= (cs - 1); i++) { if (cid[i] == t) continue; int p0 = pos[c[cid[i]]], p1 = i; p0 -= p0 >= tp, p1 -= p1 >= tp; int di = (p1 - p0 + cs - 1) % (cs - 1); if (d != -1 && d != di) NO(); d = di; } int dst = dis(s, t); long long d1 = (long long)cs * d + dst, d2 = (long long)cs * (cs - 1) - d1; long long ans = dis(s0, s) + dis(t0, t) + min(d1, d2); cout << min(A, B) << " " << max(A, B) << " " << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } const int oo = 0x3f3f3f3f; const int maxn = 200000; struct edge { int id, nxt; edge() {} edge(int _id, int _nxt) : id(_id), nxt(_nxt) {} }; edge e[(maxn << 1) + 5]; int st[maxn + 5], en = 0; inline void add_edge(int first, int second) { e[en] = edge(second, st[first]), st[first] = en++; } int n; int dep[maxn + 5], fa[maxn + 5]; int dfs_tot = 0; int dfn[maxn + 5], End[maxn + 5]; void dfs(int first, int f = -1) { if (~f) dep[first] = dep[f] + 1; else dep[first] = 0; dfn[first] = dfs_tot++; fa[first] = f; for (int i = st[first]; i != -1; i = e[i].nxt) { int second = e[i].id; if (second == f) continue; dfs(second, first); } End[first] = dfs_tot; } int pa, push_back; int a[maxn + 5], b[maxn + 5]; int main() { memset(st, -1, sizeof st), en = 0; scanf("%d", &n); for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", a + i); pa = find(a, a + n, 0) - a; for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", b + i); push_back = find(b, b + n, 0) - b; for (int i = (0), _end_ = (n - 1); i < _end_; ++i) { int first, second; scanf("%d%d", &first, &second), --first, --second; add_edge(first, second), add_edge(second, first); } dfs(push_back); int u = pa; while (u != push_back) { a[u] = a[fa[u]]; u = fa[u]; } a[u] = 0; int first = -1, rt = -1; int cnt = 0; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i]) { ++cnt; if (!~rt || dep[i] < dep[rt]) rt = i; if (!~first || dep[i] > dep[first]) first = i; } if (!cnt) printf("0 %d\n", dep[pa]), exit(0); rt = fa[rt]; int second = rt; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i] && (End[i] <= dfn[first] || dfn[i] > dfn[first]) && dep[i] > dep[second]) second = i; if (dep[first] + dep[second] - (dep[rt] << 1) != cnt) printf("-1\n"), exit(0); vector<int> all; int id = first; while (id != rt) { all.push_back(id); id = fa[id]; } reverse((all).begin(), (all).end()); id = second; while (id != rt) { all.push_back(id); id = fa[id]; } int go = -1; for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[0]] == b[all[i]]) { go = i; break; } if (!~go) printf("-1\n"), exit(0); for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[i]] != b[all[(i + go) % (int((all).size()))]]) printf("-1\n"), exit(0); long long ans = dep[pa]; static bool vis[maxn + 5]; memset(vis, 0, sizeof vis); id = pa; while (~id) { vis[id] = 1; id = fa[id]; } if (vis[all[0]] || vis[all.back()]) { if (vis[all.back()]) reverse((all).begin(), (all).end()), go = (int((all).size())) - go; int tmp = (int((all).size())); for (int i = (1), _end_ = ((int((all).size()))); i < _end_; ++i) if (!vis[all[i]]) { tmp = i; break; } int cyc_len = (int((all).size())) + 1; ans -= tmp; ans += min(abs(tmp + (long long)go * cyc_len), abs(tmp + (long long)(go - (int((all).size()))) * cyc_len)); } else ans += min(go, (int((all).size())) - go) * (cnt + 1); id = rt; while (!vis[id]) { ans += 2; id = fa[id]; } if (first > second) swap(first, second); printf("%d %d %I64d\n", first + 1, second + 1, ans); return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } const int oo = 0x3f3f3f3f; const int maxn = 200000; struct edge { int id, nxt; edge() {} edge(int _id, int _nxt) : id(_id), nxt(_nxt) {} }; edge e[(maxn << 1) + 5]; int st[maxn + 5], en = 0; inline void add_edge(int first, int second) { e[en] = edge(second, st[first]), st[first] = en++; } int n; int dep[maxn + 5], fa[maxn + 5]; int dfs_tot = 0; int dfn[maxn + 5], End[maxn + 5]; void dfs(int first, int f = -1) { if (~f) dep[first] = dep[f] + 1; else dep[first] = 0; dfn[first] = dfs_tot++; fa[first] = f; for (int i = st[first]; i != -1; i = e[i].nxt) { int second = e[i].id; if (second == f) continue; dfs(second, first); } End[first] = dfs_tot; } int pa, push_back; int a[maxn + 5], b[maxn + 5]; int main() { memset(st, -1, sizeof st), en = 0; scanf("%d", &n); for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", a + i); pa = find(a, a + n, 0) - a; for (int i = (0), _end_ = (n); i < _end_; ++i) scanf("%d", b + i); push_back = find(b, b + n, 0) - b; for (int i = (0), _end_ = (n - 1); i < _end_; ++i) { int first, second; scanf("%d%d", &first, &second), --first, --second; add_edge(first, second), add_edge(second, first); } dfs(push_back); int u = pa; while (u != push_back) { a[u] = a[fa[u]]; u = fa[u]; } a[u] = 0; int first = -1, rt = -1; int cnt = 0; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i]) { ++cnt; if (!~rt || dep[i] < dep[rt]) rt = i; if (!~first || dep[i] > dep[first]) first = i; } if (!cnt) printf("0 %d\n", dep[pa]), exit(0); rt = fa[rt]; int second = rt; for (int i = (0), _end_ = (n); i < _end_; ++i) if (a[i] != b[i] && (End[i] <= dfn[first] || dfn[i] > dfn[first]) && dep[i] > dep[second]) second = i; if (dep[first] + dep[second] - (dep[rt] << 1) != cnt) printf("-1\n"), exit(0); vector<int> all; int id = first; while (id != rt) { all.push_back(id); id = fa[id]; } reverse((all).begin(), (all).end()); id = second; while (id != rt) { all.push_back(id); id = fa[id]; } int go = -1; for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[0]] == b[all[i]]) { go = i; break; } if (!~go) printf("-1\n"), exit(0); for (int i = (0), _end_ = ((int((all).size()))); i < _end_; ++i) if (a[all[i]] != b[all[(i + go) % (int((all).size()))]]) printf("-1\n"), exit(0); long long ans = dep[pa]; static bool vis[maxn + 5]; memset(vis, 0, sizeof vis); id = pa; while (~id) { vis[id] = 1; id = fa[id]; } if (vis[all[0]] || vis[all.back()]) { if (vis[all.back()]) reverse((all).begin(), (all).end()), go = (int((all).size())) - go; int tmp = (int((all).size())); for (int i = (1), _end_ = ((int((all).size()))); i < _end_; ++i) if (!vis[all[i]]) { tmp = i; break; } int cyc_len = (int((all).size())) + 1; ans -= tmp; ans += min(abs(tmp + (long long)go * cyc_len), abs(tmp + (long long)(go - (int((all).size()))) * cyc_len)); } else ans += min(go, (int((all).size())) - go) * (cnt + 1); id = rt; while (!vis[id]) { ans += 2; id = fa[id]; } if (first > second) swap(first, second); printf("%d %d %I64d\n", first + 1, second + 1, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f = ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 200005; int n, s0, t0, s, t, tp; vector<int> e[N], ch[N]; int a[N], b[N], c[N], f[N]; deque<int> id; int find(int *a, int v) { for (int i = (1); i <= (n); i++) if (a[i] == v) return i; return 0; } int check(int *a, int *b) { for (int i = (1); i <= (n); i++) if (a[i] != b[i]) return 0; return 1; } int fa[N], dep[N], anc[N][20]; void dfs(int x, int pre = 0, int d = 0) { anc[x][0] = fa[x] = pre, dep[x] = d; for (int i = (1); i <= (19); i++) anc[x][i] = anc[anc[x][i - 1]][i - 1]; for (auto y : e[x]) if (y != pre) dfs(y, x, d + 1); } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = (19); i >= (0); i--) if (dep[x] - (1 << i) >= dep[y]) x = anc[x][i]; if (x == y) return x; for (int i = (19); i >= (0); i--) if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i]; return fa[x]; } int dis(int x, int y) { return dep[x] + dep[y] - 2 * dep[LCA(x, y)]; } void NO() { puts("-1"); exit(0); } vector<int> cid; void dfs_ch(int x, int pre = 0) { cid.push_back(x); if (x == t) tp = (int)cid.size() - 1; for (auto y : ch[x]) if (y != pre) dfs_ch(y, x); } int main() { n = read(); for (int i = (1); i <= (n); i++) a[i] = read(); for (int i = (1); i <= (n); i++) b[i] = read(); for (int i = (1); i <= (n - 1); i++) { int x = read(), y = read(); e[x].push_back(y), e[y].push_back(x); } s0 = find(a, 0), t0 = find(b, 0); dfs(t0); for (int i = (1); i <= (n); i++) c[i] = a[i]; for (int x = s0; x != t0; x = fa[x]) id.push_back(x), swap(c[x], c[fa[x]]); id.push_back(t0); if (check(b, c)) printf("0 %d\n", dep[s0]), exit(0); deque<int> ID = id; while ((int)id.size() >= 2 && b[id[0]] == c[id[0]]) id.pop_front(); while ((int)id.size() >= 2 && b[id[(int)id.size() - 2]] == c[id[(int)id.size() - 2]]) id.pop_back(); assert(!id.empty()); s = id.front(), t = id.back(); if (b[id[0]] != c[id[0]]) { for (auto i : id) f[i] = 1; } else { int x = -1; for (int i = (1); i <= (n); i++) if (b[i] != c[i]) if (x == -1 || dis(i, t0) < dis(x, t0)) x = i; assert(x != -1); for (auto y : e[x]) if (dis(y, t0) < dis(x, t0)) { f[s = t = y] = 1; break; } assert(s != 0); } for (int i = (1); i <= (n); i++) if (b[i] != c[i]) f[i] = 1; for (int i = (1); i <= (n); i++) for (auto j : e[i]) if (f[i] && f[j]) ch[i].push_back(j); int A = -1, B = -1; for (int i = (1); i <= (n); i++) if (ch[i].size() > 2) NO(); else if (ch[i].size() == 1) { if (A == -1) A = i; else if (B == -1) B = i; else NO(); } else if (ch[i].empty() && f[i]) NO(); if (B == -1) NO(); if (dis(B, s) < dis(B, t)) swap(A, B); b[t] = c[t] = 0; dfs_ch(A); vector<int> pos(n + 1, -1); int cs = (int)cid.size(); for (int i = (0); i <= (cs - 1); i++) pos[b[cid[i]]] = i; int d = -1; for (int i = (0); i <= (cs - 1); i++) { if (cid[i] == t) continue; int p0 = pos[c[cid[i]]], p1 = i; p0 -= p0 >= tp, p1 -= p1 >= tp; int di = (p1 - p0 + cs - 1) % (cs - 1); if (d != -1 && d != di) NO(); d = di; } int dst = dis(s, t); long long d1 = (long long)cs * d + dst, d2 = (long long)cs * (cs - 1) - d1; long long ans = dis(s0, s) + dis(t0, t) + min(d1, d2); cout << min(A, B) << " " << max(A, B) << " " << ans << endl; return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f = ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 200005; int n, s0, t0, s, t, tp; vector<int> e[N], ch[N]; int a[N], b[N], c[N], f[N]; deque<int> id; int find(int *a, int v) { for (int i = (1); i <= (n); i++) if (a[i] == v) return i; return 0; } int check(int *a, int *b) { for (int i = (1); i <= (n); i++) if (a[i] != b[i]) return 0; return 1; } int fa[N], dep[N], anc[N][20]; void dfs(int x, int pre = 0, int d = 0) { anc[x][0] = fa[x] = pre, dep[x] = d; for (int i = (1); i <= (19); i++) anc[x][i] = anc[anc[x][i - 1]][i - 1]; for (auto y : e[x]) if (y != pre) dfs(y, x, d + 1); } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = (19); i >= (0); i--) if (dep[x] - (1 << i) >= dep[y]) x = anc[x][i]; if (x == y) return x; for (int i = (19); i >= (0); i--) if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i]; return fa[x]; } int dis(int x, int y) { return dep[x] + dep[y] - 2 * dep[LCA(x, y)]; } void NO() { puts("-1"); exit(0); } vector<int> cid; void dfs_ch(int x, int pre = 0) { cid.push_back(x); if (x == t) tp = (int)cid.size() - 1; for (auto y : ch[x]) if (y != pre) dfs_ch(y, x); } int main() { n = read(); for (int i = (1); i <= (n); i++) a[i] = read(); for (int i = (1); i <= (n); i++) b[i] = read(); for (int i = (1); i <= (n - 1); i++) { int x = read(), y = read(); e[x].push_back(y), e[y].push_back(x); } s0 = find(a, 0), t0 = find(b, 0); dfs(t0); for (int i = (1); i <= (n); i++) c[i] = a[i]; for (int x = s0; x != t0; x = fa[x]) id.push_back(x), swap(c[x], c[fa[x]]); id.push_back(t0); if (check(b, c)) printf("0 %d\n", dep[s0]), exit(0); deque<int> ID = id; while ((int)id.size() >= 2 && b[id[0]] == c[id[0]]) id.pop_front(); while ((int)id.size() >= 2 && b[id[(int)id.size() - 2]] == c[id[(int)id.size() - 2]]) id.pop_back(); assert(!id.empty()); s = id.front(), t = id.back(); if (b[id[0]] != c[id[0]]) { for (auto i : id) f[i] = 1; } else { int x = -1; for (int i = (1); i <= (n); i++) if (b[i] != c[i]) if (x == -1 || dis(i, t0) < dis(x, t0)) x = i; assert(x != -1); for (auto y : e[x]) if (dis(y, t0) < dis(x, t0)) { f[s = t = y] = 1; break; } assert(s != 0); } for (int i = (1); i <= (n); i++) if (b[i] != c[i]) f[i] = 1; for (int i = (1); i <= (n); i++) for (auto j : e[i]) if (f[i] && f[j]) ch[i].push_back(j); int A = -1, B = -1; for (int i = (1); i <= (n); i++) if (ch[i].size() > 2) NO(); else if (ch[i].size() == 1) { if (A == -1) A = i; else if (B == -1) B = i; else NO(); } else if (ch[i].empty() && f[i]) NO(); if (B == -1) NO(); if (dis(B, s) < dis(B, t)) swap(A, B); b[t] = c[t] = 0; dfs_ch(A); vector<int> pos(n + 1, -1); int cs = (int)cid.size(); for (int i = (0); i <= (cs - 1); i++) pos[b[cid[i]]] = i; int d = -1; for (int i = (0); i <= (cs - 1); i++) { if (cid[i] == t) continue; int p0 = pos[c[cid[i]]], p1 = i; p0 -= p0 >= tp, p1 -= p1 >= tp; int di = (p1 - p0 + cs - 1) % (cs - 1); if (d != -1 && d != di) NO(); d = di; } int dst = dis(s, t); long long d1 = (long long)cs * d + dst, d2 = (long long)cs * (cs - 1) - d1; long long ans = dis(s0, s) + dis(t0, t) + min(d1, d2); cout << min(A, B) << " " << max(A, B) << " " << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; void fail() { puts("-1"), exit(0); } int O_A[200011], A_B[200011], A_O[200011], B_A[200011]; int tot, fi[200011]; struct edge { int nx, to; } e[200011 * 4]; void ps(int x, int y) { e[++tot] = (edge){fi[x], y}; fi[x] = tot; } int ft[200011], dep[200011]; void dfs_base(int x, int fa) { ft[x] = fa; for (int i = fi[x], y; (y = e[i].to); i = e[i].nx) if (y != fa) dep[y] = dep[x] + 1, dfs_base(y, x); return; } int C[200011], n; bool check() { for (int i = 1; i <= n; i++) C[i] = A_B[i]; int now = B_A[1]; while (ft[now]) swap(C[now], C[ft[now]]), now = ft[now]; for (int i = 1; i <= n; i++) { if (C[i] != i) return 0; } return 1; } vector<int> cir[2]; int Cnt = 0; void Chain(int x) { if (Cnt > 1 || (Cnt == 1 && ft[x] != ft[cir[0][0]])) fail(); int t; do { t = 0; for (int i = fi[x], y; (y = e[i].to); i = e[i].nx) if (C[y] != y && y != ft[x]) { if (!t) t = y; else fail(); } cir[Cnt].push_back(x); x = t; } while (x); ++Cnt; } void dfs_sd(int x, int fa) { for (int i = fi[x], y; (y = e[i].to); i = e[i].nx) if (y != fa) { if (C[y] == y) dfs_sd(y, x); else Chain(y); } } int len, Cir_P[200011], P[200011]; int getdis(int x, int y) { int dd = 0; while (x != y) { if (dep[x] < dep[y]) swap(x, y); x = ft[x]; ++dd; } return dd; } void work() { for (int i = 1; i <= n; i++) Cir_P[i] = -1; for (int i = 0; i < (int)cir[0].size(); i++) { P[len] = C[cir[0][i]]; Cir_P[cir[0][i]] = len; ++len; } int ru = cir[0].back(), rv = ft[cir[0].front()]; int tp = rv; if (cir[1].size()) { rv = cir[1].back(); for (int i = cir[1].size() - 1; i >= 0; i--) { P[len] = C[cir[1][i]]; Cir_P[cir[1][i]] = len; ++len; } } ru = A_O[ru]; rv = A_O[rv]; if (ru > rv) swap(ru, rv); long long dis = Cir_P[P[0]]; for (int i = 1; i < len; i++) { if ((Cir_P[P[i]] - i + len) % len != dis) fail(); } for (int i = 1; i <= n; i++) { if (C[i] != i && Cir_P[i] == -1) fail(); } int tmp = B_A[1]; while (Cir_P[tmp] == -1 && tmp != 1) tmp = ft[tmp]; printf("%d %d ", ru, rv); if (tmp == 1) { dis = min(dis, len - dis) * (len + 1); printf("%lld", dis + getdis(B_A[1], tp) + dep[tp]); return; } if (Cir_P[tmp] >= (int)cir[0].size()) { dis = min((dis - 1) * (len + 1) + (Cir_P[tmp] + 1), (len - dis) * (len + 1) + (len - Cir_P[tmp])); } else { dis = min(dis * (len + 1) + (Cir_P[tmp] + 1), (len - dis - 1) * (len + 1) + (len - Cir_P[tmp])); } printf("%lld", dis + getdis(B_A[1], tmp) + dep[tp]); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &O_A[i]), ++O_A[i], A_O[O_A[i]] = i; for (int i = 1; i <= n; i++) scanf("%d", &A_B[O_A[i]]), ++A_B[O_A[i]]; for (int i = 1, x, y; i < n; i++) { scanf("%d%d", &x, &y); x = O_A[x]; y = O_A[y]; ps(x, y); ps(y, x); } for (int i = 1; i <= n; i++) B_A[A_B[i]] = i; dfs_base(1, 0); if (check()) { printf("%d %d", 0, dep[B_A[1]]); return 0; } dfs_sd(1, 0); work(); }
### Prompt Your task is to create a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void fail() { puts("-1"), exit(0); } int O_A[200011], A_B[200011], A_O[200011], B_A[200011]; int tot, fi[200011]; struct edge { int nx, to; } e[200011 * 4]; void ps(int x, int y) { e[++tot] = (edge){fi[x], y}; fi[x] = tot; } int ft[200011], dep[200011]; void dfs_base(int x, int fa) { ft[x] = fa; for (int i = fi[x], y; (y = e[i].to); i = e[i].nx) if (y != fa) dep[y] = dep[x] + 1, dfs_base(y, x); return; } int C[200011], n; bool check() { for (int i = 1; i <= n; i++) C[i] = A_B[i]; int now = B_A[1]; while (ft[now]) swap(C[now], C[ft[now]]), now = ft[now]; for (int i = 1; i <= n; i++) { if (C[i] != i) return 0; } return 1; } vector<int> cir[2]; int Cnt = 0; void Chain(int x) { if (Cnt > 1 || (Cnt == 1 && ft[x] != ft[cir[0][0]])) fail(); int t; do { t = 0; for (int i = fi[x], y; (y = e[i].to); i = e[i].nx) if (C[y] != y && y != ft[x]) { if (!t) t = y; else fail(); } cir[Cnt].push_back(x); x = t; } while (x); ++Cnt; } void dfs_sd(int x, int fa) { for (int i = fi[x], y; (y = e[i].to); i = e[i].nx) if (y != fa) { if (C[y] == y) dfs_sd(y, x); else Chain(y); } } int len, Cir_P[200011], P[200011]; int getdis(int x, int y) { int dd = 0; while (x != y) { if (dep[x] < dep[y]) swap(x, y); x = ft[x]; ++dd; } return dd; } void work() { for (int i = 1; i <= n; i++) Cir_P[i] = -1; for (int i = 0; i < (int)cir[0].size(); i++) { P[len] = C[cir[0][i]]; Cir_P[cir[0][i]] = len; ++len; } int ru = cir[0].back(), rv = ft[cir[0].front()]; int tp = rv; if (cir[1].size()) { rv = cir[1].back(); for (int i = cir[1].size() - 1; i >= 0; i--) { P[len] = C[cir[1][i]]; Cir_P[cir[1][i]] = len; ++len; } } ru = A_O[ru]; rv = A_O[rv]; if (ru > rv) swap(ru, rv); long long dis = Cir_P[P[0]]; for (int i = 1; i < len; i++) { if ((Cir_P[P[i]] - i + len) % len != dis) fail(); } for (int i = 1; i <= n; i++) { if (C[i] != i && Cir_P[i] == -1) fail(); } int tmp = B_A[1]; while (Cir_P[tmp] == -1 && tmp != 1) tmp = ft[tmp]; printf("%d %d ", ru, rv); if (tmp == 1) { dis = min(dis, len - dis) * (len + 1); printf("%lld", dis + getdis(B_A[1], tp) + dep[tp]); return; } if (Cir_P[tmp] >= (int)cir[0].size()) { dis = min((dis - 1) * (len + 1) + (Cir_P[tmp] + 1), (len - dis) * (len + 1) + (len - Cir_P[tmp])); } else { dis = min(dis * (len + 1) + (Cir_P[tmp] + 1), (len - dis - 1) * (len + 1) + (len - Cir_P[tmp])); } printf("%lld", dis + getdis(B_A[1], tmp) + dep[tp]); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &O_A[i]), ++O_A[i], A_O[O_A[i]] = i; for (int i = 1; i <= n; i++) scanf("%d", &A_B[O_A[i]]), ++A_B[O_A[i]]; for (int i = 1, x, y; i < n; i++) { scanf("%d%d", &x, &y); x = O_A[x]; y = O_A[y]; ps(x, y); ps(y, x); } for (int i = 1; i <= n; i++) B_A[A_B[i]] = i; dfs_base(1, 0); if (check()) { printf("%d %d", 0, dep[B_A[1]]); return 0; } dfs_sd(1, 0); work(); } ```
#include <bits/stdc++.h> using namespace std; int read(); int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } const int _SIZE = 1 << 22; char ibuf[_SIZE], *iS = ibuf, *iT = ibuf; int read() { int x = 0, f = 1; char c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (!isdigit(c)) f = (c == '-') ? -1 : f, c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (isdigit(c)) x = x * 10 + c - '0', c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); return x * f; }
### Prompt Create a solution in CPP for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int read(); int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } const int _SIZE = 1 << 22; char ibuf[_SIZE], *iS = ibuf, *iT = ibuf; int read() { int x = 0, f = 1; char c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (!isdigit(c)) f = (c == '-') ? -1 : f, c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (isdigit(c)) x = x * 10 + c - '0', c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); return x * f; } ```
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 200000; const int MAXM = MAXN - 1; typedef struct E { int u, v; } E; bool operator<(const E &a, const E &b) { if (a.u != b.u) return a.u < b.u; return a.v < b.v; } int n; int oa[MAXN], ob[MAXN]; int a[MAXN], ra[MAXN]; int b[MAXN], rb[MAXN]; bool been[MAXN]; bool d[MAXN]; E e[MAXM]; int adj[MAXN][2], nadj[MAXN]; int p[2][MAXN], np[2], nnp; bool onp[MAXN]; int c[MAXN], rc[MAXN], nc; int head[MAXN], nxt[2 * MAXM], to[2 * MAXM]; int t[MAXN]; bool exists(int u, int v) { if (u > v) swap(u, v); int l = 0, h = n - 1; while (l <= h) { int m = l + (h - l) / 2; if (e[m].u == u && e[m].v == v) return true; if (e[m].u < u || e[m].u == u && e[m].v < v) l = m + 1; else h = m - 1; } return false; } int dfs(int at, int par) { if (been[at]) return 0; int ret = INT_MAX; for (int x = head[at]; x != -1; x = nxt[x]) { if (onp[to[x]] || to[x] == par) continue; int cur = dfs(to[x], at); if (cur == INT_MAX) continue; if (cur + 1 < ret) ret = cur + 1; } return ret; } void run() { scanf("%d", &n); for (int i = (0); i < (n); ++i) scanf("%d", &a[i]); for (int i = (0); i < (n); ++i) ra[a[i]] = i; for (int i = (0); i < (n); ++i) scanf("%d", &b[i]); for (int i = (0); i < (n); ++i) rb[b[i]] = i; for (int i = (0); i < (n - 1); ++i) { scanf("%d%d", &e[i].u, &e[i].v); --e[i].u, --e[i].v; if (e[i].u > e[i].v) swap(e[i].u, e[i].v); } sort(e, e + n - 1); for (int i = (0); i < (n); ++i) been[i] = false, head[i] = -1, oa[i] = a[i], ob[i] = b[i]; for (int i = (0); i < (n - 1); ++i) { int u = e[i].u, v = e[i].v; nxt[2 * i + 0] = head[u]; head[u] = 2 * i + 0; to[2 * i + 0] = v; nxt[2 * i + 1] = head[v]; head[v] = 2 * i + 1; to[2 * i + 1] = u; } int ret = 0; while (true) { int u = ra[0], v = ra[b[u]]; been[u] = true; if (!exists(u, v)) break; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ret; } while (true) { int u = rb[0], v = rb[a[u]]; if (!exists(u, v)) break; swap(b[u], b[v]); swap(rb[b[u]], rb[b[v]]); ++ret; } for (int i = (0); i < (n); ++i) d[i] = a[i] != b[i], nadj[i] = 0, onp[i] = false; nnp = 0; for (int i = (0); i < (n - 1); ++i) if (d[e[i].u] && d[e[i].v]) { int u = e[i].u, v = e[i].v; if (nadj[u] == 2) { printf("-1\n"); return; } else adj[u][nadj[u]++] = v; if (nadj[v] == 2) { printf("-1\n"); return; } else adj[v][nadj[v]++] = u; } for (int i = (0); i < (n); ++i) if (d[i] && nadj[i] <= 1 && !onp[i]) { if (nnp == 2) { printf("-1\n"); return; } else np[nnp] = 0; for (int at = i, to = -1; at != -1; at = to, to = -1) { p[nnp][np[nnp]++] = at; onp[at] = true; for (int j = (0); j < (nadj[at]); ++j) if (!onp[adj[at][j]]) to = adj[at][j]; } ++nnp; } if (nnp == 0) { printf("0 %d\n", ret); return; } if (nnp == 2) for (int i = (0); i < (n); ++i) if (!onp[i] && (exists(i, p[0][0]) || exists(i, p[0][np[0] - 1])) && (exists(i, p[1][0]) || exists(i, p[1][np[1] - 1]))) { if (!exists(i, p[0][np[0] - 1])) reverse(p[0], p[0] + np[0]); if (!exists(i, p[1][0])) reverse(p[1], p[1] + np[1]); p[0][np[0]++] = i; onp[i] = true; for (int j = (0); j < (np[1]); ++j) p[0][np[0]++] = p[1][j]; nnp = 1; break; } if (nnp == 2) { if (np[0] == 1 && np[1] == 1) { printf("%d %d %d\n", min(p[0][0], p[1][0]) + 1, max(p[0][0], p[1][0]) + 1, ret + 1); return; } printf("-1\n"); return; } nc = np[0]; for (int i = (0); i < (nc); ++i) c[i] = p[0][i]; memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; int ccwret = 0, fixidx = -1; if (onp[ra[0]] && onp[rb[0]]) { int idx = rc[ra[0]]; assert(idx != -1); while (ra[0] != rb[0]) { int nidx = idx == nc - 1 ? 0 : idx + 1, u = c[idx], v = c[nidx]; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ccwret; idx = nidx; } fixidx = idx; } else { int dst = INT_MAX; for (int i = (0); i < (nc); ++i) if (been[c[i]] && a[c[i]] == b[c[i]]) dst = 0, fixidx = i; for (int i = (0); i < (nc); ++i) for (int x = head[c[i]]; dst == INT_MAX && x != -1; x = nxt[x]) if (!onp[to[x]]) { int cur = dfs(to[x], i); if (cur == INT_MAX) continue; if (a[c[i]] == b[c[i]]) { dst = cur + 1, fixidx = i; } if (a[c[i]] != b[c[i]]) { if (i != 0 && i != nc - 1) { printf("-1\n"); return; } if (i == 0) reverse(c, c + nc); c[nc++] = to[x]; dst = cur, fixidx = nc - 1; } } assert(dst != INT_MAX); ret += 2 * dst; } memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; if (a[c[fixidx]] != b[c[fixidx]]) { printf("-1\n"); return; } t[fixidx] = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) { int to = rc[rb[a[c[i]]]]; if (to == -1) { printf("-1\n"); return; } if (to < i) to += nc; t[i] = to - i; if (to > fixidx && i < fixidx || i > fixidx && to > nc + fixidx) --t[i]; } int tall = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) if (tall == -1) tall = t[i]; else if (t[i] != tall) { printf("-1\n"); return; } long long ret1 = ret + ccwret + (long long)nc * (nc - 1 - tall); long long ret2 = ret + nc - ccwret + (long long)nc * (tall - 1); printf("%d %d %I64d\n", min(c[0], c[nc - 1]) + 1, max(c[0], c[nc - 1]) + 1, min(ret1, ret2)); } int main() { run(); return 0; }
### Prompt Please create a solution in cpp to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 200000; const int MAXM = MAXN - 1; typedef struct E { int u, v; } E; bool operator<(const E &a, const E &b) { if (a.u != b.u) return a.u < b.u; return a.v < b.v; } int n; int oa[MAXN], ob[MAXN]; int a[MAXN], ra[MAXN]; int b[MAXN], rb[MAXN]; bool been[MAXN]; bool d[MAXN]; E e[MAXM]; int adj[MAXN][2], nadj[MAXN]; int p[2][MAXN], np[2], nnp; bool onp[MAXN]; int c[MAXN], rc[MAXN], nc; int head[MAXN], nxt[2 * MAXM], to[2 * MAXM]; int t[MAXN]; bool exists(int u, int v) { if (u > v) swap(u, v); int l = 0, h = n - 1; while (l <= h) { int m = l + (h - l) / 2; if (e[m].u == u && e[m].v == v) return true; if (e[m].u < u || e[m].u == u && e[m].v < v) l = m + 1; else h = m - 1; } return false; } int dfs(int at, int par) { if (been[at]) return 0; int ret = INT_MAX; for (int x = head[at]; x != -1; x = nxt[x]) { if (onp[to[x]] || to[x] == par) continue; int cur = dfs(to[x], at); if (cur == INT_MAX) continue; if (cur + 1 < ret) ret = cur + 1; } return ret; } void run() { scanf("%d", &n); for (int i = (0); i < (n); ++i) scanf("%d", &a[i]); for (int i = (0); i < (n); ++i) ra[a[i]] = i; for (int i = (0); i < (n); ++i) scanf("%d", &b[i]); for (int i = (0); i < (n); ++i) rb[b[i]] = i; for (int i = (0); i < (n - 1); ++i) { scanf("%d%d", &e[i].u, &e[i].v); --e[i].u, --e[i].v; if (e[i].u > e[i].v) swap(e[i].u, e[i].v); } sort(e, e + n - 1); for (int i = (0); i < (n); ++i) been[i] = false, head[i] = -1, oa[i] = a[i], ob[i] = b[i]; for (int i = (0); i < (n - 1); ++i) { int u = e[i].u, v = e[i].v; nxt[2 * i + 0] = head[u]; head[u] = 2 * i + 0; to[2 * i + 0] = v; nxt[2 * i + 1] = head[v]; head[v] = 2 * i + 1; to[2 * i + 1] = u; } int ret = 0; while (true) { int u = ra[0], v = ra[b[u]]; been[u] = true; if (!exists(u, v)) break; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ret; } while (true) { int u = rb[0], v = rb[a[u]]; if (!exists(u, v)) break; swap(b[u], b[v]); swap(rb[b[u]], rb[b[v]]); ++ret; } for (int i = (0); i < (n); ++i) d[i] = a[i] != b[i], nadj[i] = 0, onp[i] = false; nnp = 0; for (int i = (0); i < (n - 1); ++i) if (d[e[i].u] && d[e[i].v]) { int u = e[i].u, v = e[i].v; if (nadj[u] == 2) { printf("-1\n"); return; } else adj[u][nadj[u]++] = v; if (nadj[v] == 2) { printf("-1\n"); return; } else adj[v][nadj[v]++] = u; } for (int i = (0); i < (n); ++i) if (d[i] && nadj[i] <= 1 && !onp[i]) { if (nnp == 2) { printf("-1\n"); return; } else np[nnp] = 0; for (int at = i, to = -1; at != -1; at = to, to = -1) { p[nnp][np[nnp]++] = at; onp[at] = true; for (int j = (0); j < (nadj[at]); ++j) if (!onp[adj[at][j]]) to = adj[at][j]; } ++nnp; } if (nnp == 0) { printf("0 %d\n", ret); return; } if (nnp == 2) for (int i = (0); i < (n); ++i) if (!onp[i] && (exists(i, p[0][0]) || exists(i, p[0][np[0] - 1])) && (exists(i, p[1][0]) || exists(i, p[1][np[1] - 1]))) { if (!exists(i, p[0][np[0] - 1])) reverse(p[0], p[0] + np[0]); if (!exists(i, p[1][0])) reverse(p[1], p[1] + np[1]); p[0][np[0]++] = i; onp[i] = true; for (int j = (0); j < (np[1]); ++j) p[0][np[0]++] = p[1][j]; nnp = 1; break; } if (nnp == 2) { if (np[0] == 1 && np[1] == 1) { printf("%d %d %d\n", min(p[0][0], p[1][0]) + 1, max(p[0][0], p[1][0]) + 1, ret + 1); return; } printf("-1\n"); return; } nc = np[0]; for (int i = (0); i < (nc); ++i) c[i] = p[0][i]; memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; int ccwret = 0, fixidx = -1; if (onp[ra[0]] && onp[rb[0]]) { int idx = rc[ra[0]]; assert(idx != -1); while (ra[0] != rb[0]) { int nidx = idx == nc - 1 ? 0 : idx + 1, u = c[idx], v = c[nidx]; swap(a[u], a[v]); swap(ra[a[u]], ra[a[v]]); ++ccwret; idx = nidx; } fixidx = idx; } else { int dst = INT_MAX; for (int i = (0); i < (nc); ++i) if (been[c[i]] && a[c[i]] == b[c[i]]) dst = 0, fixidx = i; for (int i = (0); i < (nc); ++i) for (int x = head[c[i]]; dst == INT_MAX && x != -1; x = nxt[x]) if (!onp[to[x]]) { int cur = dfs(to[x], i); if (cur == INT_MAX) continue; if (a[c[i]] == b[c[i]]) { dst = cur + 1, fixidx = i; } if (a[c[i]] != b[c[i]]) { if (i != 0 && i != nc - 1) { printf("-1\n"); return; } if (i == 0) reverse(c, c + nc); c[nc++] = to[x]; dst = cur, fixidx = nc - 1; } } assert(dst != INT_MAX); ret += 2 * dst; } memset(rc, -1, sizeof(rc)); for (int i = (0); i < (nc); ++i) rc[c[i]] = i; if (a[c[fixidx]] != b[c[fixidx]]) { printf("-1\n"); return; } t[fixidx] = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) { int to = rc[rb[a[c[i]]]]; if (to == -1) { printf("-1\n"); return; } if (to < i) to += nc; t[i] = to - i; if (to > fixidx && i < fixidx || i > fixidx && to > nc + fixidx) --t[i]; } int tall = -1; for (int i = (0); i < (nc); ++i) if (i != fixidx) if (tall == -1) tall = t[i]; else if (t[i] != tall) { printf("-1\n"); return; } long long ret1 = ret + ccwret + (long long)nc * (nc - 1 - tall); long long ret2 = ret + nc - ccwret + (long long)nc * (tall - 1); printf("%d %d %I64d\n", min(c[0], c[nc - 1]) + 1, max(c[0], c[nc - 1]) + 1, min(ret1, ret2)); } int main() { run(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; struct Edge { int to, next; } edge[N << 1]; int n, start, finish, tot, rt, st1, end1; int st[N], a[N], b[N], depth[N], fa[N], vis[N]; long long ans; vector<int> loop; void link(int u, int v) { edge[++tot].to = v; edge[tot].next = st[u]; st[u] = tot; } void dfs(int x, int from) { fa[x] = from, depth[x] = depth[from] + 1; for (int l = st[x]; l; l = edge[l].next) if (edge[l].to != from) dfs(edge[l].to, x); } int find() { loop.clear(); int d1 = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && depth[i] > depth[d1]) d1 = i; if (!d1) return 1; for (int x = d1; vis[x] = 1, loop.push_back(x), a[fa[x]] != b[fa[x]]; x = fa[x]) ; int d2 = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && depth[i] > depth[d2]) d2 = i; if (d2) { reverse(loop.begin(), loop.end()); for (int x = d2; vis[x] = 1, loop.push_back(x), a[fa[x]] != b[fa[x]]; x = fa[x]) ; } else d2 = fa[loop.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; int u = d1, v = d2; for (; u != v; u = fa[u]) if (depth[u] < depth[v]) swap(u, v); rt = u; if (loop.size() != depth[d1] + depth[d2] - 2 * depth[rt]) return 0; st1 = d1, end1 = d2; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) start = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) finish = i; } for (int i = 1, u, v; i < n; i++) scanf("%d%d", &u, &v), link(u, v), link(v, u); depth[0] = -1; dfs(finish, 0); for (int x = start; x != finish; x = fa[x]) swap(a[x], a[fa[x]]); ans = depth[start]; if (!find()) { printf("-1\n"); return 0; } if (!loop.size()) { printf("0 %I64d\n", ans); return 0; } int pos = 0, siz = loop.size(); for (int i = 0; i < siz; i++) if (b[loop[i]] == a[loop[0]]) pos = i; for (int i = 1; i < siz; i++) if (b[loop[(i + pos) % siz]] != a[loop[i]]) { printf("-1\n"); return 0; } memset(vis, 0, sizeof(vis)); for (int x = start; x; x = fa[x]) vis[x] = 1; if (vis[loop[0]] || vis[loop.back()]) { int p = siz; for (int i = 0; i < siz; i++) if (!vis[loop[i]]) { p = i; break; } ans = ans - p + min(p + pos * 1LL * (siz + 1), abs((siz - pos) * 1LL * (siz + 1) - p)); } else ans = (ans + min(pos, siz - pos) * 1LL * (siz + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (st1 > end1) swap(st1, end1); printf("%d %d %I64d\n", st1, end1, ans); return 0; }
### Prompt Construct a CPP code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; struct Edge { int to, next; } edge[N << 1]; int n, start, finish, tot, rt, st1, end1; int st[N], a[N], b[N], depth[N], fa[N], vis[N]; long long ans; vector<int> loop; void link(int u, int v) { edge[++tot].to = v; edge[tot].next = st[u]; st[u] = tot; } void dfs(int x, int from) { fa[x] = from, depth[x] = depth[from] + 1; for (int l = st[x]; l; l = edge[l].next) if (edge[l].to != from) dfs(edge[l].to, x); } int find() { loop.clear(); int d1 = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && depth[i] > depth[d1]) d1 = i; if (!d1) return 1; for (int x = d1; vis[x] = 1, loop.push_back(x), a[fa[x]] != b[fa[x]]; x = fa[x]) ; int d2 = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && depth[i] > depth[d2]) d2 = i; if (d2) { reverse(loop.begin(), loop.end()); for (int x = d2; vis[x] = 1, loop.push_back(x), a[fa[x]] != b[fa[x]]; x = fa[x]) ; } else d2 = fa[loop.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; int u = d1, v = d2; for (; u != v; u = fa[u]) if (depth[u] < depth[v]) swap(u, v); rt = u; if (loop.size() != depth[d1] + depth[d2] - 2 * depth[rt]) return 0; st1 = d1, end1 = d2; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) start = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) finish = i; } for (int i = 1, u, v; i < n; i++) scanf("%d%d", &u, &v), link(u, v), link(v, u); depth[0] = -1; dfs(finish, 0); for (int x = start; x != finish; x = fa[x]) swap(a[x], a[fa[x]]); ans = depth[start]; if (!find()) { printf("-1\n"); return 0; } if (!loop.size()) { printf("0 %I64d\n", ans); return 0; } int pos = 0, siz = loop.size(); for (int i = 0; i < siz; i++) if (b[loop[i]] == a[loop[0]]) pos = i; for (int i = 1; i < siz; i++) if (b[loop[(i + pos) % siz]] != a[loop[i]]) { printf("-1\n"); return 0; } memset(vis, 0, sizeof(vis)); for (int x = start; x; x = fa[x]) vis[x] = 1; if (vis[loop[0]] || vis[loop.back()]) { int p = siz; for (int i = 0; i < siz; i++) if (!vis[loop[i]]) { p = i; break; } ans = ans - p + min(p + pos * 1LL * (siz + 1), abs((siz - pos) * 1LL * (siz + 1) - p)); } else ans = (ans + min(pos, siz - pos) * 1LL * (siz + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (st1 > end1) swap(st1, end1); printf("%d %d %I64d\n", st1, end1, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, m, i, j, a[200005], b[200005], c[200005], d[200005], pa[200005], pb[200005], vis[200005], fa[200005], dep[200005], dfn[200005], ti, p, p1, p2, f[200005], tp; bool incir[200005]; vector<int> bi[200005], nd[200005], ed; long long ans, c1, c2; vector<int> cir, tmp, all; int lca(int p1, int p2) { while (dep[p1] > dep[p2]) { p1 = fa[p1]; } while (dep[p2] > dep[p1]) { p2 = fa[p2]; } while (p1 != p2) { p1 = fa[p1]; p2 = fa[p2]; } return p1; } void dfs1(int x, int p) { fa[x] = p; dfn[x] = ++ti; for (__typeof((bi[x]).begin()) it = (bi[x]).begin(); it != (bi[x]).end(); it++) { if (*it == p) continue; dep[*it] = dep[x] + 1; dfs1(*it, x); } } void dfs2(int x, int p) { f[x] = vis[x]; for (__typeof((bi[x]).begin()) it = (bi[x]).begin(); it != (bi[x]).end(); it++) { if (*it == p) continue; dfs2(*it, x); f[x] |= f[*it]; if (f[*it]) nd[x].push_back(*it); } } void dfs3(int x) { if (nd[x].empty()) ed.push_back(x); for (__typeof((nd[x]).begin()) it = (nd[x]).begin(); it != (nd[x]).end(); it++) dfs3(*it); } void dfs4(int x, int p) { fa[x] = p; for (__typeof((bi[x]).begin()) it = (bi[x]).begin(); it != (bi[x]).end(); it++) { if (*it == p || incir[*it]) continue; dfs4(*it, x); } } long long solve() { long long ans = 0; int i, j; for ((i) = 0; (i) < (m); ++(i)) { if (a[i] == 0) break; } for ((j) = 0; (j) < (m); ++(j)) { if (b[j] == 0) break; } while (i != j) { ans++; swap(a[i], a[(i + 1) % m]); i++; i %= m; } int c1 = 0, c2 = 0; for ((i) = 0; (i) < (m); ++(i)) { if (a[i]) pa[a[i]] = ++c1; if (b[i]) pb[b[i]] = ++c2; } int t = pa[1] - pb[1]; if (t < 0) t += m - 1; for ((i) = (2); (i) <= (m - 1); ++(i)) { int tt = pa[i] - pb[i]; if (tt < 0) tt += m - 1; if (t != tt) { puts("-1"); exit(0); } } ans += 1ll * t * m; return ans; } int main() { scanf("%d", &n); for ((i) = 1; (i) <= (n); ++(i)) scanf("%d", &a[i]); for ((i) = 1; (i) <= (n); ++(i)) scanf("%d", &b[i]); for ((i) = 1; (i) <= (n - 1); ++(i)) { int x, y; scanf("%d%d", &x, &y); bi[x].push_back(y); bi[y].push_back(x); } dfs1(1, 0); for ((i) = 1; (i) <= (n); ++(i)) c[i] = a[i]; for ((i) = 1; (i) <= (n); ++(i)) d[i] = b[i]; for ((i) = 1; (i) <= (n); ++(i)) if (a[i] == 0) { p = i; break; } while (p != 1) { swap(c[p], c[fa[p]]); p = fa[p]; } for ((i) = 1; (i) <= (n); ++(i)) if (b[i] == 0) { p = i; break; } while (p != 1) { swap(d[p], d[fa[p]]); p = fa[p]; } bool s0 = 1; int mi = 0, mx = 0; for ((i) = 1; (i) <= (n); ++(i)) { if (c[i] != d[i]) { vis[i] = 1; s0 = 0; if (!mi || dfn[i] < dfn[mi]) mi = i; if (!mx || dfn[i] > dfn[mx]) mx = i; } } if (s0) { printf("0 "); for ((i) = 1; (i) <= (n); ++(i)) if (a[i] == 0) { p1 = i; break; } for ((i) = 1; (i) <= (n); ++(i)) if (b[i] == 0) { p2 = i; break; } while (dep[p1] > dep[p2]) { p1 = fa[p1]; ans++; } while (dep[p2] > dep[p1]) { p2 = fa[p2]; ans++; } while (p1 != p2) { p1 = fa[p1]; p2 = fa[p2]; ans += 2; } printf("%lld\n", ans); return 0; } tp = lca(mi, mx); if (tp == mi) tp = fa[tp]; dfs2(tp, fa[tp]); if (nd[tp].size() > 2) { puts("-1"); return 0; } for ((i) = 1; (i) <= (n); ++(i)) if (i != tp && nd[i].size() > 1) { puts("-1"); return 0; } dfs3(tp); if (nd[tp].size() == 1) nd[tp].push_back(tp); p1 = nd[tp][0]; while (!nd[p1].empty()) p1 = nd[p1][0]; while (p1 != tp) { cir.push_back(p1); p1 = fa[p1]; } cir.push_back(tp); p2 = nd[tp][1]; while (p2 != tp && !nd[p2].empty()) p2 = nd[p2][0]; while (p2 != tp) { tmp.push_back(p2); p2 = fa[p2]; } while (!tmp.empty()) { cir.push_back(tmp.back()); tmp.pop_back(); } m = cir.size(); for ((i) = 1; (i) <= (n); ++(i)) if (a[i] == 0) { p1 = i; break; } for ((i) = 1; (i) <= (n); ++(i)) if (b[i] == 0) { p2 = i; break; } for (__typeof((cir).begin()) it = (cir).begin(); it != (cir).end(); it++) { incir[*it] = 1; } for (__typeof((cir).begin()) it = (cir).begin(); it != (cir).end(); it++) dfs4(*it, 0); while (!incir[p1]) { swap(a[p1], a[fa[p1]]); p1 = fa[p1]; ans++; } while (!incir[p2]) { swap(b[p2], b[fa[p2]]); p2 = fa[p2]; ans++; } for ((i) = 0; (i) < (m); ++(i)) { c[i] = a[cir[i]]; d[i] = b[cir[i]]; } all.clear(); for ((i) = 0; (i) < (m); ++(i)) all.push_back(c[i]); sort(all.begin(), all.end()); all.resize(unique(all.begin(), all.end()) - all.begin()); for ((i) = 0; (i) < (m); ++(i)) { a[i] = c[i] = lower_bound(all.begin(), all.end(), c[i]) - all.begin(); } all.clear(); for ((i) = 0; (i) < (m); ++(i)) all.push_back(d[i]); sort(all.begin(), all.end()); all.resize(unique(all.begin(), all.end()) - all.begin()); for ((i) = 0; (i) < (m); ++(i)) { b[i] = d[i] = lower_bound(all.begin(), all.end(), d[i]) - all.begin(); } c1 = solve(); reverse(c, c + m); reverse(d, d + m); for ((i) = 0; (i) < (m); ++(i)) { a[i] = c[i]; b[i] = d[i]; } c2 = solve(); p1 = nd[tp][0]; while (!nd[p1].empty()) p1 = nd[p1][0]; p2 = nd[tp][1]; while (p2 != tp && !nd[p2].empty()) p2 = nd[p2][0]; printf("%d %d %lld\n", min(p1, p2), max(p1, p2), ans + min(c1, c2)); return 0; }
### Prompt Generate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, m, i, j, a[200005], b[200005], c[200005], d[200005], pa[200005], pb[200005], vis[200005], fa[200005], dep[200005], dfn[200005], ti, p, p1, p2, f[200005], tp; bool incir[200005]; vector<int> bi[200005], nd[200005], ed; long long ans, c1, c2; vector<int> cir, tmp, all; int lca(int p1, int p2) { while (dep[p1] > dep[p2]) { p1 = fa[p1]; } while (dep[p2] > dep[p1]) { p2 = fa[p2]; } while (p1 != p2) { p1 = fa[p1]; p2 = fa[p2]; } return p1; } void dfs1(int x, int p) { fa[x] = p; dfn[x] = ++ti; for (__typeof((bi[x]).begin()) it = (bi[x]).begin(); it != (bi[x]).end(); it++) { if (*it == p) continue; dep[*it] = dep[x] + 1; dfs1(*it, x); } } void dfs2(int x, int p) { f[x] = vis[x]; for (__typeof((bi[x]).begin()) it = (bi[x]).begin(); it != (bi[x]).end(); it++) { if (*it == p) continue; dfs2(*it, x); f[x] |= f[*it]; if (f[*it]) nd[x].push_back(*it); } } void dfs3(int x) { if (nd[x].empty()) ed.push_back(x); for (__typeof((nd[x]).begin()) it = (nd[x]).begin(); it != (nd[x]).end(); it++) dfs3(*it); } void dfs4(int x, int p) { fa[x] = p; for (__typeof((bi[x]).begin()) it = (bi[x]).begin(); it != (bi[x]).end(); it++) { if (*it == p || incir[*it]) continue; dfs4(*it, x); } } long long solve() { long long ans = 0; int i, j; for ((i) = 0; (i) < (m); ++(i)) { if (a[i] == 0) break; } for ((j) = 0; (j) < (m); ++(j)) { if (b[j] == 0) break; } while (i != j) { ans++; swap(a[i], a[(i + 1) % m]); i++; i %= m; } int c1 = 0, c2 = 0; for ((i) = 0; (i) < (m); ++(i)) { if (a[i]) pa[a[i]] = ++c1; if (b[i]) pb[b[i]] = ++c2; } int t = pa[1] - pb[1]; if (t < 0) t += m - 1; for ((i) = (2); (i) <= (m - 1); ++(i)) { int tt = pa[i] - pb[i]; if (tt < 0) tt += m - 1; if (t != tt) { puts("-1"); exit(0); } } ans += 1ll * t * m; return ans; } int main() { scanf("%d", &n); for ((i) = 1; (i) <= (n); ++(i)) scanf("%d", &a[i]); for ((i) = 1; (i) <= (n); ++(i)) scanf("%d", &b[i]); for ((i) = 1; (i) <= (n - 1); ++(i)) { int x, y; scanf("%d%d", &x, &y); bi[x].push_back(y); bi[y].push_back(x); } dfs1(1, 0); for ((i) = 1; (i) <= (n); ++(i)) c[i] = a[i]; for ((i) = 1; (i) <= (n); ++(i)) d[i] = b[i]; for ((i) = 1; (i) <= (n); ++(i)) if (a[i] == 0) { p = i; break; } while (p != 1) { swap(c[p], c[fa[p]]); p = fa[p]; } for ((i) = 1; (i) <= (n); ++(i)) if (b[i] == 0) { p = i; break; } while (p != 1) { swap(d[p], d[fa[p]]); p = fa[p]; } bool s0 = 1; int mi = 0, mx = 0; for ((i) = 1; (i) <= (n); ++(i)) { if (c[i] != d[i]) { vis[i] = 1; s0 = 0; if (!mi || dfn[i] < dfn[mi]) mi = i; if (!mx || dfn[i] > dfn[mx]) mx = i; } } if (s0) { printf("0 "); for ((i) = 1; (i) <= (n); ++(i)) if (a[i] == 0) { p1 = i; break; } for ((i) = 1; (i) <= (n); ++(i)) if (b[i] == 0) { p2 = i; break; } while (dep[p1] > dep[p2]) { p1 = fa[p1]; ans++; } while (dep[p2] > dep[p1]) { p2 = fa[p2]; ans++; } while (p1 != p2) { p1 = fa[p1]; p2 = fa[p2]; ans += 2; } printf("%lld\n", ans); return 0; } tp = lca(mi, mx); if (tp == mi) tp = fa[tp]; dfs2(tp, fa[tp]); if (nd[tp].size() > 2) { puts("-1"); return 0; } for ((i) = 1; (i) <= (n); ++(i)) if (i != tp && nd[i].size() > 1) { puts("-1"); return 0; } dfs3(tp); if (nd[tp].size() == 1) nd[tp].push_back(tp); p1 = nd[tp][0]; while (!nd[p1].empty()) p1 = nd[p1][0]; while (p1 != tp) { cir.push_back(p1); p1 = fa[p1]; } cir.push_back(tp); p2 = nd[tp][1]; while (p2 != tp && !nd[p2].empty()) p2 = nd[p2][0]; while (p2 != tp) { tmp.push_back(p2); p2 = fa[p2]; } while (!tmp.empty()) { cir.push_back(tmp.back()); tmp.pop_back(); } m = cir.size(); for ((i) = 1; (i) <= (n); ++(i)) if (a[i] == 0) { p1 = i; break; } for ((i) = 1; (i) <= (n); ++(i)) if (b[i] == 0) { p2 = i; break; } for (__typeof((cir).begin()) it = (cir).begin(); it != (cir).end(); it++) { incir[*it] = 1; } for (__typeof((cir).begin()) it = (cir).begin(); it != (cir).end(); it++) dfs4(*it, 0); while (!incir[p1]) { swap(a[p1], a[fa[p1]]); p1 = fa[p1]; ans++; } while (!incir[p2]) { swap(b[p2], b[fa[p2]]); p2 = fa[p2]; ans++; } for ((i) = 0; (i) < (m); ++(i)) { c[i] = a[cir[i]]; d[i] = b[cir[i]]; } all.clear(); for ((i) = 0; (i) < (m); ++(i)) all.push_back(c[i]); sort(all.begin(), all.end()); all.resize(unique(all.begin(), all.end()) - all.begin()); for ((i) = 0; (i) < (m); ++(i)) { a[i] = c[i] = lower_bound(all.begin(), all.end(), c[i]) - all.begin(); } all.clear(); for ((i) = 0; (i) < (m); ++(i)) all.push_back(d[i]); sort(all.begin(), all.end()); all.resize(unique(all.begin(), all.end()) - all.begin()); for ((i) = 0; (i) < (m); ++(i)) { b[i] = d[i] = lower_bound(all.begin(), all.end(), d[i]) - all.begin(); } c1 = solve(); reverse(c, c + m); reverse(d, d + m); for ((i) = 0; (i) < (m); ++(i)) { a[i] = c[i]; b[i] = d[i]; } c2 = solve(); p1 = nd[tp][0]; while (!nd[p1].empty()) p1 = nd[p1][0]; p2 = nd[tp][1]; while (p2 != tp && !nd[p2].empty()) p2 = nd[p2][0]; printf("%d %d %lld\n", min(p1, p2), max(p1, p2), ans + min(c1, c2)); return 0; } ```
#include <bits/stdc++.h> using namespace std; void no() { printf("-1"); exit(0); } struct bian { int nxt, to; } bi[400040]; int n, a[200020], b[200020], head[200020], num, c[200020], f[200020]; inline void add(int from, int to) { bi[++num] = bian{head[from], to}; head[from] = num; } int st[200020], tp; bool vis[200020], used[200020]; long long ans, res; void bfs(int s, int e) { static int q[200020], h, t, x, y; memset(vis + 1, 0, n); h = 0, t = 1, q[t] = e, vis[e] = 1, f[e] = 0; while (h < t) { x = q[++h]; for (int i = head[x]; i; i = bi[i].nxt) { y = bi[i].to; if (!vis[y]) vis[y] = 1, q[++t] = y, f[y] = x; } } x = s; tp = 0; while (x) st[++tp] = x, x = f[x]; } int cnt, siz[200020], dep[200020]; void dfs(int v, int fa) { dep[v] = dep[fa] + 1; f[v] = fa; siz[v] = b[v] != c[v]; int d = 0; for (int i = head[v], u; i; i = bi[i].nxt) { u = bi[i].to; if (u == fa) continue; dfs(u, v); siz[v] += siz[u]; if (siz[u]) ++d; } if (d >= 3 || (d == 2 && siz[v] != cnt)) no(); } int pa[200020], plen; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= n; ++i) scanf("%d", &b[i]); int x, y, z, w; for (int i = 1; i < n; ++i) { scanf("%d %d", &x, &y); add(x, y), add(y, x); } memcpy(c + 1, a + 1, n << 2); for (int i = 1; i <= n; ++i) { if (c[i] == 0) x = i; if (b[i] == 0) y = i; } bfs(x, y); z = x; w = y; for (int i = 2; i <= tp; ++i) used[st[i]] = 1; res = tp - 1; for (int i = 1; i < tp; ++i) c[st[i]] = c[st[i + 1]]; c[st[tp]] = 0; for (int i = 1; i <= n; ++i) cnt += b[i] != c[i]; if (!cnt) return printf("0 %d", tp - 1), 0; dfs(y, 0); memset(vis + 1, 0, n); int p = 0, q = 0; for (int i = 1; i <= n; ++i) if (b[i] != c[i] && dep[i] > dep[p]) p = i; tp = 0; x = p; while (b[x] != c[x]) st[++tp] = x, vis[x] = 1, x = f[x]; for (int i = 1; i <= n; ++i) if (b[i] != c[i] && !vis[i] && dep[i] > dep[q]) q = i; int cur = tp; y = q; while (b[y] != c[y] && !vis[y]) st[++tp] = y, vis[y] = 1, y = f[y]; if (!q) q = y = x; if (x != y) no(); for (int i = 1; i <= n; ++i) if (b[i] != c[i] && !vis[i]) no(); reverse(st + cur + 1, st + tp + 1); int len; for (int i = 1; i <= tp; ++i) if (c[st[1]] == b[st[i]]) len = i - 1; for (int i = 1; i <= tp; ++i) if (c[st[i]] != b[st[(i + len - 1) % tp + 1]]) no(); memcpy(pa + 1, st + 1, tp << 2); plen = tp; bfs(z, x); for (int i = 2; i <= tp; ++i) if (!used[st[i]]) res += 2; long long s = res; for (int i = tp - 1, j = cur; i > 0 && j > 0; --i, --j) if (st[i] == pa[j]) s -= 2; else break; ans = s + 1ll * len * (plen + 1); s = res; for (int i = tp - 1, j = cur + 1; i > 0; --i, ++j) if (st[i] == pa[j]) s -= 2; else break; ans = min(ans, s + 1ll * (plen - len) * (plen + 1)); if (p > q) swap(p, q); printf("%d %d %lld", p, q, ans); return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void no() { printf("-1"); exit(0); } struct bian { int nxt, to; } bi[400040]; int n, a[200020], b[200020], head[200020], num, c[200020], f[200020]; inline void add(int from, int to) { bi[++num] = bian{head[from], to}; head[from] = num; } int st[200020], tp; bool vis[200020], used[200020]; long long ans, res; void bfs(int s, int e) { static int q[200020], h, t, x, y; memset(vis + 1, 0, n); h = 0, t = 1, q[t] = e, vis[e] = 1, f[e] = 0; while (h < t) { x = q[++h]; for (int i = head[x]; i; i = bi[i].nxt) { y = bi[i].to; if (!vis[y]) vis[y] = 1, q[++t] = y, f[y] = x; } } x = s; tp = 0; while (x) st[++tp] = x, x = f[x]; } int cnt, siz[200020], dep[200020]; void dfs(int v, int fa) { dep[v] = dep[fa] + 1; f[v] = fa; siz[v] = b[v] != c[v]; int d = 0; for (int i = head[v], u; i; i = bi[i].nxt) { u = bi[i].to; if (u == fa) continue; dfs(u, v); siz[v] += siz[u]; if (siz[u]) ++d; } if (d >= 3 || (d == 2 && siz[v] != cnt)) no(); } int pa[200020], plen; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= n; ++i) scanf("%d", &b[i]); int x, y, z, w; for (int i = 1; i < n; ++i) { scanf("%d %d", &x, &y); add(x, y), add(y, x); } memcpy(c + 1, a + 1, n << 2); for (int i = 1; i <= n; ++i) { if (c[i] == 0) x = i; if (b[i] == 0) y = i; } bfs(x, y); z = x; w = y; for (int i = 2; i <= tp; ++i) used[st[i]] = 1; res = tp - 1; for (int i = 1; i < tp; ++i) c[st[i]] = c[st[i + 1]]; c[st[tp]] = 0; for (int i = 1; i <= n; ++i) cnt += b[i] != c[i]; if (!cnt) return printf("0 %d", tp - 1), 0; dfs(y, 0); memset(vis + 1, 0, n); int p = 0, q = 0; for (int i = 1; i <= n; ++i) if (b[i] != c[i] && dep[i] > dep[p]) p = i; tp = 0; x = p; while (b[x] != c[x]) st[++tp] = x, vis[x] = 1, x = f[x]; for (int i = 1; i <= n; ++i) if (b[i] != c[i] && !vis[i] && dep[i] > dep[q]) q = i; int cur = tp; y = q; while (b[y] != c[y] && !vis[y]) st[++tp] = y, vis[y] = 1, y = f[y]; if (!q) q = y = x; if (x != y) no(); for (int i = 1; i <= n; ++i) if (b[i] != c[i] && !vis[i]) no(); reverse(st + cur + 1, st + tp + 1); int len; for (int i = 1; i <= tp; ++i) if (c[st[1]] == b[st[i]]) len = i - 1; for (int i = 1; i <= tp; ++i) if (c[st[i]] != b[st[(i + len - 1) % tp + 1]]) no(); memcpy(pa + 1, st + 1, tp << 2); plen = tp; bfs(z, x); for (int i = 2; i <= tp; ++i) if (!used[st[i]]) res += 2; long long s = res; for (int i = tp - 1, j = cur; i > 0 && j > 0; --i, --j) if (st[i] == pa[j]) s -= 2; else break; ans = s + 1ll * len * (plen + 1); s = res; for (int i = tp - 1, j = cur + 1; i > 0; --i, ++j) if (st[i] == pa[j]) s -= 2; else break; ans = min(ans, s + 1ll * (plen - len) * (plen + 1)); if (p > q) swap(p, q); printf("%d %d %lld", p, q, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> sosedi[maxn]; int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n; bool visit_vertex[maxn]; void dfs(int v, int predok) { parent[v] = predok; shagi[v] = shagi[predok] + 1; for (auto daleko1 : sosedi[v]) if (daleko1 != predok) dfs(daleko1, v); } vector<int> circles; int rt, st1, end1; bool find_circle() { circles.clear(); int daleko1 = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && shagi[i] > shagi[daleko1]) daleko1 = i; if (!daleko1) return 1; for (int u = daleko1; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; int daleko2 = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[daleko2]) daleko2 = i; if (daleko2) { reverse(circles.begin(), circles.end()); for (int u = daleko2; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; } else daleko2 = parent[circles.back()]; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i]) return 0; int u, v; for (u = daleko1, v = daleko2; u != v; u = parent[u]) if (shagi[u] < shagi[v]) swap(u, v); rt = u; if (circles.size() != shagi[daleko1] + shagi[daleko2] - 2 * shagi[rt]) return 0; st1 = daleko1, end1 = daleko2; return 1; } int main() { cin >> n; int st_empty_ped, end_empty_ped; for (int i = 1; i <= n; i++) { cin >> start[i]; if (start[i] == 0) st_empty_ped = i; } for (int i = 1; i <= n; i++) { cin >> finish[i]; if (finish[i] == 0) end_empty_ped = i; } for (int i = 1, u, v; i < n; i++) { cin >> u >> v; sosedi[u].push_back(v), sosedi[v].push_back(u); } shagi[0] = -1; dfs(end_empty_ped, 0); for (int u = st_empty_ped; u != end_empty_ped; u = parent[u]) swap(start[u], start[parent[u]]); long long answer = shagi[st_empty_ped]; if (!find_circle()) { cout << -1 << endl; return 0; } if (!circles.size()) { cout << 0 << " " << answer << " " << endl; return 0; } int no_vis_vertex = 0, lenght = circles.size(); for (int i = 0; i < lenght; i++) if (finish[circles[i]] == start[circles[0]]) no_vis_vertex = i; for (int i = 1; i < lenght; i++) if (finish[circles[(i + no_vis_vertex) % lenght]] != start[circles[i]]) { printf("-1\n"); return 0; } memset(visit_vertex, false, maxn); for (int i = st_empty_ped; i; i = parent[i]) visit_vertex[i] = 1; if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) { int po = circles.size(); for (int i = 0; i < circles.size(); i++) if (!visit_vertex[circles[i]]) { po = i; break; } answer = answer - po + min(po + no_vis_vertex * 1ll * (lenght + 1), abs((lenght - no_vis_vertex) * 1ll * (lenght + 1) - po)); } else answer = (answer + min(no_vis_vertex, lenght - no_vis_vertex) * 1ll * (lenght + 1)); for (; !visit_vertex[rt]; rt = parent[rt]) answer += 2; if (st1 > end1) swap(end1, st1); cout << st1 << " " << end1 << " " << answer << " " << endl; return 0; }
### Prompt Create a solution in CPP for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> sosedi[maxn]; int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n; bool visit_vertex[maxn]; void dfs(int v, int predok) { parent[v] = predok; shagi[v] = shagi[predok] + 1; for (auto daleko1 : sosedi[v]) if (daleko1 != predok) dfs(daleko1, v); } vector<int> circles; int rt, st1, end1; bool find_circle() { circles.clear(); int daleko1 = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && shagi[i] > shagi[daleko1]) daleko1 = i; if (!daleko1) return 1; for (int u = daleko1; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; int daleko2 = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[daleko2]) daleko2 = i; if (daleko2) { reverse(circles.begin(), circles.end()); for (int u = daleko2; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; } else daleko2 = parent[circles.back()]; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i]) return 0; int u, v; for (u = daleko1, v = daleko2; u != v; u = parent[u]) if (shagi[u] < shagi[v]) swap(u, v); rt = u; if (circles.size() != shagi[daleko1] + shagi[daleko2] - 2 * shagi[rt]) return 0; st1 = daleko1, end1 = daleko2; return 1; } int main() { cin >> n; int st_empty_ped, end_empty_ped; for (int i = 1; i <= n; i++) { cin >> start[i]; if (start[i] == 0) st_empty_ped = i; } for (int i = 1; i <= n; i++) { cin >> finish[i]; if (finish[i] == 0) end_empty_ped = i; } for (int i = 1, u, v; i < n; i++) { cin >> u >> v; sosedi[u].push_back(v), sosedi[v].push_back(u); } shagi[0] = -1; dfs(end_empty_ped, 0); for (int u = st_empty_ped; u != end_empty_ped; u = parent[u]) swap(start[u], start[parent[u]]); long long answer = shagi[st_empty_ped]; if (!find_circle()) { cout << -1 << endl; return 0; } if (!circles.size()) { cout << 0 << " " << answer << " " << endl; return 0; } int no_vis_vertex = 0, lenght = circles.size(); for (int i = 0; i < lenght; i++) if (finish[circles[i]] == start[circles[0]]) no_vis_vertex = i; for (int i = 1; i < lenght; i++) if (finish[circles[(i + no_vis_vertex) % lenght]] != start[circles[i]]) { printf("-1\n"); return 0; } memset(visit_vertex, false, maxn); for (int i = st_empty_ped; i; i = parent[i]) visit_vertex[i] = 1; if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) { int po = circles.size(); for (int i = 0; i < circles.size(); i++) if (!visit_vertex[circles[i]]) { po = i; break; } answer = answer - po + min(po + no_vis_vertex * 1ll * (lenght + 1), abs((lenght - no_vis_vertex) * 1ll * (lenght + 1) - po)); } else answer = (answer + min(no_vis_vertex, lenght - no_vis_vertex) * 1ll * (lenght + 1)); for (; !visit_vertex[rt]; rt = parent[rt]) answer += 2; if (st1 > end1) swap(end1, st1); cout << st1 << " " << end1 << " " << answer << " " << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const long long INF = 1LL << 60; long long powmod(long long a, long long b) { long long res = 1; a %= 1000000007; for (; b; b >>= 1) { if (b & 1) res = res * a % 1000000007; a = a * a % 1000000007; } return res; } template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int n; vector<int> g[500000]; int s[500000], t[500000], tmps[500000], tmpt[500000]; int fa[500000], dep[500000], cir[500000]; void dfs(int u) { for (auto v : g[u]) { if (v == fa[u] || cir[v]) continue; fa[v] = u; dep[v] = dep[u] + 1; dfs(v); } } int vis[500000], tmp[500000], on[500000]; int ansu, ansv; int main() { n = read(); int ss, tt; for (int i = 1; i <= n; i++) { s[i] = read(); if (s[i] == 0) ss = i; } for (int i = 1; i <= n; i++) { t[i] = read(); if (t[i] == 0) tt = i; } for (int i = 1; i < n; i++) { int u = read(), v = read(); g[u].push_back(v); g[v].push_back(u); } dfs(tt); int now = ss; for (int i = 1; i <= n; i++) tmp[i] = s[i]; while (now != tt) { swap(tmp[now], tmp[fa[now]]); now = fa[now]; } int ok = 0; for (int i = 1; i <= n; i++) ok |= tmp[i] != t[i]; if (!ok) { printf("0 %d\n", dep[ss]); return 0; } for (int i = 1; i <= n; i++) vis[i] = tmp[i] != t[i]; int a[4], b[4], tot; for (tot = 0; tot <= 2;) { int k = 0; for (int i = 1; i <= n; i++) if (vis[i]) { k = i; break; } if (!k) break; int now = k; while (true) { vis[now] = 0; int mark = 0; for (auto v : g[now]) { if (vis[v]) { now = v; mark = 1; break; } } if (!mark) break; } a[++tot] = now; now = k; while (true) { vis[now] = 0; int mark = 0; for (auto v : g[now]) { if (vis[v]) { now = v; mark = 1; break; } } if (!mark) break; } b[tot] = now; } if (tot > 2) { puts("-1"); return 0; } if (tot == 1) { int &u = a[1], &v = b[1]; if (dep[u] > dep[v]) swap(u, v); int now = v; while (now && now != u) now = fa[now]; if (!now) { puts("-1"); return 0; } g[fa[u]].push_back(v), g[v].push_back(fa[u]); ansu = fa[u], ansv = v; now = v; while (now != fa[u]) cir[now] = 1, now = fa[now]; cir[fa[u]] = 1; } else { for (int i = 1; i <= 2; i++) { int &u = a[i], &v = b[i]; if (dep[u] > dep[v]) swap(u, v); int now = v; while (now && now != u) now = fa[now]; if (!now) { puts("-1"); return 0; } } if (fa[a[1]] != fa[a[2]]) { puts("-1"); return 0; } g[b[1]].push_back(b[2]), g[b[2]].push_back(b[1]); ansu = b[1], ansv = b[2]; for (int i = 1; i <= 2; i++) { int now = b[i]; while (now != fa[a[i]]) cir[now] = 1, now = fa[now]; cir[fa[a[i]]] = 1; } } for (int i = 1; i <= n; i++) if (cir[i]) { fa[i] = 0; dfs(i); } long long ans = 0; while (!cir[ss]) swap(s[ss], s[fa[ss]]), ss = fa[ss], ans++; while (!cir[tt]) swap(t[tt], t[fa[tt]]), tt = fa[tt], ans++; now = ss, tot = 0; while (true) { cir[now] = 0; on[tot++] = now; int tmp = now; for (auto v : g[now]) { if (cir[v]) { now = v; break; } } if (now == tmp) break; } long long res = INF; int pos = 0; for (int i = 0; i < tot; i++) if (on[i] == tt) pos = i; for (int _ = -1; _ <= 1; _ += 2) { memcpy(tmps, s, sizeof s); memcpy(tmpt, t, sizeof t); int tmp = 0; if (pos) for (int i = pos; i < tot && i; i += _) swap(tmpt[on[i]], tmpt[on[(i + _) % tot]]), tmp++; int ii = 1, jj = 0, circle; for (int i = 1; i < tot; i++) if (tmpt[on[i]] == tmps[on[1]]) jj = i; circle = jj; for (int i = 1; i < tot; i++) { if (tmpt[on[jj]] != tmps[on[ii]]) { puts("-1"); return 0; } ii += 1; jj += 1; if (ii == tot) ii = 1; if (jj == tot) jj = 1; } chkmin(res, 1LL * tot * (min(tot - circle, circle - 1)) + tmp); } if (ansu > ansv) swap(ansu, ansv); printf("%d %d %lld\n", ansu, ansv, ans + res); return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long INF = 1LL << 60; long long powmod(long long a, long long b) { long long res = 1; a %= 1000000007; for (; b; b >>= 1) { if (b & 1) res = res * a % 1000000007; a = a * a % 1000000007; } return res; } template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int n; vector<int> g[500000]; int s[500000], t[500000], tmps[500000], tmpt[500000]; int fa[500000], dep[500000], cir[500000]; void dfs(int u) { for (auto v : g[u]) { if (v == fa[u] || cir[v]) continue; fa[v] = u; dep[v] = dep[u] + 1; dfs(v); } } int vis[500000], tmp[500000], on[500000]; int ansu, ansv; int main() { n = read(); int ss, tt; for (int i = 1; i <= n; i++) { s[i] = read(); if (s[i] == 0) ss = i; } for (int i = 1; i <= n; i++) { t[i] = read(); if (t[i] == 0) tt = i; } for (int i = 1; i < n; i++) { int u = read(), v = read(); g[u].push_back(v); g[v].push_back(u); } dfs(tt); int now = ss; for (int i = 1; i <= n; i++) tmp[i] = s[i]; while (now != tt) { swap(tmp[now], tmp[fa[now]]); now = fa[now]; } int ok = 0; for (int i = 1; i <= n; i++) ok |= tmp[i] != t[i]; if (!ok) { printf("0 %d\n", dep[ss]); return 0; } for (int i = 1; i <= n; i++) vis[i] = tmp[i] != t[i]; int a[4], b[4], tot; for (tot = 0; tot <= 2;) { int k = 0; for (int i = 1; i <= n; i++) if (vis[i]) { k = i; break; } if (!k) break; int now = k; while (true) { vis[now] = 0; int mark = 0; for (auto v : g[now]) { if (vis[v]) { now = v; mark = 1; break; } } if (!mark) break; } a[++tot] = now; now = k; while (true) { vis[now] = 0; int mark = 0; for (auto v : g[now]) { if (vis[v]) { now = v; mark = 1; break; } } if (!mark) break; } b[tot] = now; } if (tot > 2) { puts("-1"); return 0; } if (tot == 1) { int &u = a[1], &v = b[1]; if (dep[u] > dep[v]) swap(u, v); int now = v; while (now && now != u) now = fa[now]; if (!now) { puts("-1"); return 0; } g[fa[u]].push_back(v), g[v].push_back(fa[u]); ansu = fa[u], ansv = v; now = v; while (now != fa[u]) cir[now] = 1, now = fa[now]; cir[fa[u]] = 1; } else { for (int i = 1; i <= 2; i++) { int &u = a[i], &v = b[i]; if (dep[u] > dep[v]) swap(u, v); int now = v; while (now && now != u) now = fa[now]; if (!now) { puts("-1"); return 0; } } if (fa[a[1]] != fa[a[2]]) { puts("-1"); return 0; } g[b[1]].push_back(b[2]), g[b[2]].push_back(b[1]); ansu = b[1], ansv = b[2]; for (int i = 1; i <= 2; i++) { int now = b[i]; while (now != fa[a[i]]) cir[now] = 1, now = fa[now]; cir[fa[a[i]]] = 1; } } for (int i = 1; i <= n; i++) if (cir[i]) { fa[i] = 0; dfs(i); } long long ans = 0; while (!cir[ss]) swap(s[ss], s[fa[ss]]), ss = fa[ss], ans++; while (!cir[tt]) swap(t[tt], t[fa[tt]]), tt = fa[tt], ans++; now = ss, tot = 0; while (true) { cir[now] = 0; on[tot++] = now; int tmp = now; for (auto v : g[now]) { if (cir[v]) { now = v; break; } } if (now == tmp) break; } long long res = INF; int pos = 0; for (int i = 0; i < tot; i++) if (on[i] == tt) pos = i; for (int _ = -1; _ <= 1; _ += 2) { memcpy(tmps, s, sizeof s); memcpy(tmpt, t, sizeof t); int tmp = 0; if (pos) for (int i = pos; i < tot && i; i += _) swap(tmpt[on[i]], tmpt[on[(i + _) % tot]]), tmp++; int ii = 1, jj = 0, circle; for (int i = 1; i < tot; i++) if (tmpt[on[i]] == tmps[on[1]]) jj = i; circle = jj; for (int i = 1; i < tot; i++) { if (tmpt[on[jj]] != tmps[on[ii]]) { puts("-1"); return 0; } ii += 1; jj += 1; if (ii == tot) ii = 1; if (jj == tot) jj = 1; } chkmin(res, 1LL * tot * (min(tot - circle, circle - 1)) + tmp); } if (ansu > ansv) swap(ansu, ansv); printf("%d %d %lld\n", ansu, ansv, ans + res); return 0; } ```
#include <bits/stdc++.h> inline int read() { char c; int x; for (c = getchar(); !isdigit(c); c = getchar()) ; for (x = 0; isdigit(c); c = getchar()) { x = x * 10 + c - '0'; } return x; } const int N = 1e6 + 5; int n, k, s, t, rs, rt, len, ans0, a[N], b[N], ft[N], dis[N], dit[N], deg[N]; long long ans1; std::vector<int> e[N], ed; bool dfs0(int u, int fa) { if (u == s) { return true; } for (auto v : e[u]) { if (v == fa) { continue; } if (dfs0(v, u)) { std::swap(a[u], a[v]); ans0++; return true; } } return false; } void dfs1(int u, int fa) { ft[u] = fa; dit[u] = dit[fa] + 1; if (a[u] != b[u]) { deg[fa]++; } for (auto v : e[u]) { if (v == fa) { continue; } dfs1(v, u); } } void dfs2(int u, int fa) { dis[u] = dis[fa] + 1; for (auto v : e[u]) { if (v == fa) { continue; } dfs2(v, u); } } bool check0() { for (int u = 1; u <= n; u++) { if (a[u] != b[u]) { return false; } } return true; } bool check1() { rt = -1; for (int u = 1; u <= n; u++) { if (a[u] == b[u]) { if (deg[u] > 2) { return false; } if (deg[u] != 0) { if (rt != -1) { return false; } rt = u; } } else { if (deg[u] > 1) { return false; } if (deg[u] == 0) { ed.push_back(u); } len++; } } if (ed.size() > 2) { return false; } if (ed.size() < 2) { ed.push_back(rt); } rs = s; for (; rs != t && a[rs] == b[rs]; rs = ft[rs]) ; if (rs == t) { rs = rt; } for (int u = ed[0]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = dit[ed[0]] - dit[u]; } } for (int u = ed[1]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = len - (dit[ed[1]] - dit[u] + 1); } } for (int u = ed[0]; u != rt; u = ft[u]) { if (u == rs) { k = len - k; } } return true; } int main() { n = read(); for (int u = 1; u <= n; u++) { a[u] = read(); if (a[u] == 0) { s = u; } } for (int u = 1; u <= n; u++) { b[u] = read(); if (b[u] == 0) { t = u; } } for (int i = 1; i < n; i++) { int u = read(), v = read(); e[u].push_back(v); e[v].push_back(u); } dfs0(t, 0); if (check0()) { printf("0 %d\n", ans0); return 0; } dis[0] = dit[0] = -1; dfs1(t, 0); dfs2(s, 0); if (!check1()) { printf("-1\n"); return 0; } if (rs == rt) { ans1 = dis[rs] + dit[rt] + 1ll * std::min(k, len - k) * (len + 1); } else { int mid = dis[rt] - dis[rs]; ans1 = dis[rs] + dit[rt] + std::min(k * (len + 1ll) - mid, (len - k) * (len + 1ll) + mid); } std::sort(ed.begin(), ed.end()); printf("%d %d %lld\n", ed[0], ed[1], ans1); return 0; }
### Prompt Your task is to create a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> inline int read() { char c; int x; for (c = getchar(); !isdigit(c); c = getchar()) ; for (x = 0; isdigit(c); c = getchar()) { x = x * 10 + c - '0'; } return x; } const int N = 1e6 + 5; int n, k, s, t, rs, rt, len, ans0, a[N], b[N], ft[N], dis[N], dit[N], deg[N]; long long ans1; std::vector<int> e[N], ed; bool dfs0(int u, int fa) { if (u == s) { return true; } for (auto v : e[u]) { if (v == fa) { continue; } if (dfs0(v, u)) { std::swap(a[u], a[v]); ans0++; return true; } } return false; } void dfs1(int u, int fa) { ft[u] = fa; dit[u] = dit[fa] + 1; if (a[u] != b[u]) { deg[fa]++; } for (auto v : e[u]) { if (v == fa) { continue; } dfs1(v, u); } } void dfs2(int u, int fa) { dis[u] = dis[fa] + 1; for (auto v : e[u]) { if (v == fa) { continue; } dfs2(v, u); } } bool check0() { for (int u = 1; u <= n; u++) { if (a[u] != b[u]) { return false; } } return true; } bool check1() { rt = -1; for (int u = 1; u <= n; u++) { if (a[u] == b[u]) { if (deg[u] > 2) { return false; } if (deg[u] != 0) { if (rt != -1) { return false; } rt = u; } } else { if (deg[u] > 1) { return false; } if (deg[u] == 0) { ed.push_back(u); } len++; } } if (ed.size() > 2) { return false; } if (ed.size() < 2) { ed.push_back(rt); } rs = s; for (; rs != t && a[rs] == b[rs]; rs = ft[rs]) ; if (rs == t) { rs = rt; } for (int u = ed[0]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = dit[ed[0]] - dit[u]; } } for (int u = ed[1]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = len - (dit[ed[1]] - dit[u] + 1); } } for (int u = ed[0]; u != rt; u = ft[u]) { if (u == rs) { k = len - k; } } return true; } int main() { n = read(); for (int u = 1; u <= n; u++) { a[u] = read(); if (a[u] == 0) { s = u; } } for (int u = 1; u <= n; u++) { b[u] = read(); if (b[u] == 0) { t = u; } } for (int i = 1; i < n; i++) { int u = read(), v = read(); e[u].push_back(v); e[v].push_back(u); } dfs0(t, 0); if (check0()) { printf("0 %d\n", ans0); return 0; } dis[0] = dit[0] = -1; dfs1(t, 0); dfs2(s, 0); if (!check1()) { printf("-1\n"); return 0; } if (rs == rt) { ans1 = dis[rs] + dit[rt] + 1ll * std::min(k, len - k) * (len + 1); } else { int mid = dis[rt] - dis[rs]; ans1 = dis[rs] + dit[rt] + std::min(k * (len + 1ll) - mid, (len - k) * (len + 1ll) + mid); } std::sort(ed.begin(), ed.end()); printf("%d %d %lld\n", ed[0], ed[1], ans1); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 5; const long long INF = 1e18; template <typename T> void chkmax(T &x, T y) { x = max(x, y); } template <typename T> void chkmin(T &x, T y) { x = min(x, y); } template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } int n, ans, tot, x[MAXN], y[MAXN]; int l, r, q[MAXN * 2], d[MAXN]; bool vis[MAXN]; vector<int> a[MAXN], rem; pair<int, int> v[MAXN]; void work(int pos) { vis[pos] = true; v[++tot] = make_pair(x[pos], y[pos]); if (pos == rem[1]) return; for (auto x : a[pos]) if (!vis[x]) work(x); } long long calc(int pos) { static pair<int, int> home[MAXN]; int cnt = 0; for (int i = 1; i <= tot; i++) if (i != pos) { home[v[i].first].first = ++cnt; home[v[i].second].second = cnt; } int x = 0, y = 0; for (int i = 1; i <= n; i++) if (home[i].first) { int tx = abs(home[i].first - home[i].second), ty = cnt - tx; if (x + y == 0) x = tx, y = ty; else if (x != tx && y != tx) return INF; } return 1ll * min(x, y) * tot; } int main() { read(n); for (int i = 1; i <= n; i++) read(x[i]); for (int i = 1; i <= n; i++) read(y[i]); for (int i = 1; i <= n - 1; i++) { int x, y; read(x), read(y); a[x].push_back(y); a[y].push_back(x); } l = 1, r = 0; for (int i = 1; i <= n; i++) { d[i] = a[i].size(); if (d[i] == 1) q[++r] = i; } while (l <= r) { int pos = q[l++]; if (x[pos] == y[pos] && x[pos] != 0) { vis[pos] = true; for (auto v : a[pos]) if (!vis[v] && --d[v] == 1) q[++r] = v; } else { int fa = 0; for (auto v : a[pos]) if (!vis[v]) fa = v; if (fa == 0) { assert(l > r); printf("%d %d\n", 0, ans); return 0; } else if (x[pos] == 0 && y[pos] == x[fa]) { swap(x[pos], x[fa]), ans++; vis[pos] = true; if (--d[fa] == 1) q[++r] = fa; } else if (y[pos] == 0 && x[pos] == y[fa]) { swap(y[pos], y[fa]), ans++; vis[pos] = true; if (--d[fa] == 1) q[++r] = fa; } else if (x[pos] == y[pos] && x[pos] == 0 && x[fa] == y[fa]) { if (rem.size() >= 2 || l > r) { swap(x[pos], x[fa]), ans++; swap(y[pos], y[fa]), ans++; vis[pos] = true; if (--d[fa] == 1) q[++r] = fa; } else q[++r] = pos; } else rem.push_back(pos); } } if (rem.size() >= 3) { puts("-1"); return 0; } assert(rem.size() == 2); if (rem[0] > rem[1]) swap(rem[0], rem[1]); long long res = INF; work(rem[0]); int x = 0, y = 0; for (int i = 1; i <= tot; i++) { if (v[i].first == 0) x = i; if (v[i].second == 0) y = i; } if (x > y) { swap(x, y); for (int i = 1; i <= tot; i++) swap(v[i].first, v[i].second); } for (int i = x + 1; i <= y; i++) swap(v[i].first, v[i - 1].first); chkmin(res, y - x + calc(y)); for (int i = y; i >= x + 1; i--) swap(v[i].first, v[i - 1].first); for (int i = x; i >= 2; i--) swap(v[i].first, v[i - 1].first); swap(v[1].first, v[tot].first); for (int i = tot; i >= y + 1; i--) swap(v[i].first, v[i - 1].first); chkmin(res, tot - (y - x) + calc(y)); if (res < INF) printf("%d %d %lld\n", rem[0], rem[1], res + ans); else puts("-1"); return 0; }
### Prompt Create a solution in cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 5; const long long INF = 1e18; template <typename T> void chkmax(T &x, T y) { x = max(x, y); } template <typename T> void chkmin(T &x, T y) { x = min(x, y); } template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } int n, ans, tot, x[MAXN], y[MAXN]; int l, r, q[MAXN * 2], d[MAXN]; bool vis[MAXN]; vector<int> a[MAXN], rem; pair<int, int> v[MAXN]; void work(int pos) { vis[pos] = true; v[++tot] = make_pair(x[pos], y[pos]); if (pos == rem[1]) return; for (auto x : a[pos]) if (!vis[x]) work(x); } long long calc(int pos) { static pair<int, int> home[MAXN]; int cnt = 0; for (int i = 1; i <= tot; i++) if (i != pos) { home[v[i].first].first = ++cnt; home[v[i].second].second = cnt; } int x = 0, y = 0; for (int i = 1; i <= n; i++) if (home[i].first) { int tx = abs(home[i].first - home[i].second), ty = cnt - tx; if (x + y == 0) x = tx, y = ty; else if (x != tx && y != tx) return INF; } return 1ll * min(x, y) * tot; } int main() { read(n); for (int i = 1; i <= n; i++) read(x[i]); for (int i = 1; i <= n; i++) read(y[i]); for (int i = 1; i <= n - 1; i++) { int x, y; read(x), read(y); a[x].push_back(y); a[y].push_back(x); } l = 1, r = 0; for (int i = 1; i <= n; i++) { d[i] = a[i].size(); if (d[i] == 1) q[++r] = i; } while (l <= r) { int pos = q[l++]; if (x[pos] == y[pos] && x[pos] != 0) { vis[pos] = true; for (auto v : a[pos]) if (!vis[v] && --d[v] == 1) q[++r] = v; } else { int fa = 0; for (auto v : a[pos]) if (!vis[v]) fa = v; if (fa == 0) { assert(l > r); printf("%d %d\n", 0, ans); return 0; } else if (x[pos] == 0 && y[pos] == x[fa]) { swap(x[pos], x[fa]), ans++; vis[pos] = true; if (--d[fa] == 1) q[++r] = fa; } else if (y[pos] == 0 && x[pos] == y[fa]) { swap(y[pos], y[fa]), ans++; vis[pos] = true; if (--d[fa] == 1) q[++r] = fa; } else if (x[pos] == y[pos] && x[pos] == 0 && x[fa] == y[fa]) { if (rem.size() >= 2 || l > r) { swap(x[pos], x[fa]), ans++; swap(y[pos], y[fa]), ans++; vis[pos] = true; if (--d[fa] == 1) q[++r] = fa; } else q[++r] = pos; } else rem.push_back(pos); } } if (rem.size() >= 3) { puts("-1"); return 0; } assert(rem.size() == 2); if (rem[0] > rem[1]) swap(rem[0], rem[1]); long long res = INF; work(rem[0]); int x = 0, y = 0; for (int i = 1; i <= tot; i++) { if (v[i].first == 0) x = i; if (v[i].second == 0) y = i; } if (x > y) { swap(x, y); for (int i = 1; i <= tot; i++) swap(v[i].first, v[i].second); } for (int i = x + 1; i <= y; i++) swap(v[i].first, v[i - 1].first); chkmin(res, y - x + calc(y)); for (int i = y; i >= x + 1; i--) swap(v[i].first, v[i - 1].first); for (int i = x; i >= 2; i--) swap(v[i].first, v[i - 1].first); swap(v[1].first, v[tot].first); for (int i = tot; i >= y + 1; i--) swap(v[i].first, v[i - 1].first); chkmin(res, tot - (y - x) + calc(y)); if (res < INF) printf("%d %d %lld\n", rem[0], rem[1], res + ans); else puts("-1"); return 0; } ```
#include <bits/stdc++.h> using namespace std; int read() { int x = 0, f = 1; char ch = getchar(); while (ch - '0' < 0 || ch - '0' > 9) { if (ch == '-') f = -1; ch = getchar(); } while (ch - '0' >= 0 && ch - '0' <= 9) { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int n; int a[200010], b[200010]; int head[200010], nxt[200010 * 2], to[200010 * 2], tot; void add(int u, int v) { tot++; nxt[tot] = head[u]; head[u] = tot; to[tot] = v; } int fa[200010], rt, on_path[200010], dep[200010], st; void dfs(int x, int las) { for (int i = head[x]; i; i = nxt[i]) { if (to[i] == las) continue; fa[to[i]] = x; dep[to[i]] = dep[x] + 1; dfs(to[i], x); } } bool cmp(int x, int y) { return dep[x] > dep[y]; } int cir[200010], top, type, Top, book[200010], bot[200010]; void check() { Top = -1; for (int i = 1; i <= top; i++) { if (book[cir[i]]) continue; type++; int x = cir[i]; bot[type] = x; while (!book[x] && a[x] != b[x]) { book[x] = 1; x = fa[x]; } if (Top == -1) Top = x; else if (Top != x) { type = 1000000007; break; } } } int s[200010], topx, cnt1, cnt2; void get(int x, int id) { topx = 0; while (x != Top) { if (on_path[x]) { if (id) cnt1++; else cnt2++; } s[++topx] = x; x = fa[x]; } if (id) reverse(s + 1, s + topx + 1); } long long calc() { int d; for (int i = 0; i < top; i++) if (b[cir[i]] == a[cir[0]]) d = i; for (int i = 0; i < top; i++) { if (a[cir[i]] != b[cir[(i + d) % top]]) return -1; } return min(1ll * d * (top + 1) - cnt2 * 2, 1ll * (top - d) * (top + 1) - cnt1 * 2); } long long ans; int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(); for (int i = 1; i <= n; i++) b[i] = read(); for (int i = 1; i < n; i++) { int q = read(), w = read(); add(q, w); add(w, q); } for (int i = 1; i <= n; i++) { if (!a[i]) st = i; if (!b[i]) rt = i; } dfs(rt, 0); int tmp = st; on_path[st] = 1; while (tmp != rt) swap(a[tmp], a[fa[tmp]]), tmp = fa[tmp], on_path[tmp] = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) cir[++top] = i; sort(cir + 1, cir + top + 1, cmp); check(); if (type > 2) { puts("-1"); return 0; } if (!type) { printf("0 %d\n", dep[st]); return 0; } top = 0; get(bot[1], 1); for (int i = 1; i <= topx; i++) cir[top++] = s[i]; if (type == 2) { get(bot[2], 0); for (int i = 1; i <= topx; i++) cir[top++] = s[i]; } ans = calc(); if (ans == -1) { puts("-1"); return 0; } tmp = Top; while (!on_path[tmp]) ans += 2, tmp = fa[tmp]; ans += dep[st]; int ansx, ansy; if (type == 1) ansx = Top, ansy = bot[1]; else ansx = bot[1], ansy = bot[2]; if (ansx > ansy) swap(ansx, ansy); cout << ansx << " " << ansy << " " << ans << endl; return 0; }
### Prompt Your task is to create a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int read() { int x = 0, f = 1; char ch = getchar(); while (ch - '0' < 0 || ch - '0' > 9) { if (ch == '-') f = -1; ch = getchar(); } while (ch - '0' >= 0 && ch - '0' <= 9) { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int n; int a[200010], b[200010]; int head[200010], nxt[200010 * 2], to[200010 * 2], tot; void add(int u, int v) { tot++; nxt[tot] = head[u]; head[u] = tot; to[tot] = v; } int fa[200010], rt, on_path[200010], dep[200010], st; void dfs(int x, int las) { for (int i = head[x]; i; i = nxt[i]) { if (to[i] == las) continue; fa[to[i]] = x; dep[to[i]] = dep[x] + 1; dfs(to[i], x); } } bool cmp(int x, int y) { return dep[x] > dep[y]; } int cir[200010], top, type, Top, book[200010], bot[200010]; void check() { Top = -1; for (int i = 1; i <= top; i++) { if (book[cir[i]]) continue; type++; int x = cir[i]; bot[type] = x; while (!book[x] && a[x] != b[x]) { book[x] = 1; x = fa[x]; } if (Top == -1) Top = x; else if (Top != x) { type = 1000000007; break; } } } int s[200010], topx, cnt1, cnt2; void get(int x, int id) { topx = 0; while (x != Top) { if (on_path[x]) { if (id) cnt1++; else cnt2++; } s[++topx] = x; x = fa[x]; } if (id) reverse(s + 1, s + topx + 1); } long long calc() { int d; for (int i = 0; i < top; i++) if (b[cir[i]] == a[cir[0]]) d = i; for (int i = 0; i < top; i++) { if (a[cir[i]] != b[cir[(i + d) % top]]) return -1; } return min(1ll * d * (top + 1) - cnt2 * 2, 1ll * (top - d) * (top + 1) - cnt1 * 2); } long long ans; int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(); for (int i = 1; i <= n; i++) b[i] = read(); for (int i = 1; i < n; i++) { int q = read(), w = read(); add(q, w); add(w, q); } for (int i = 1; i <= n; i++) { if (!a[i]) st = i; if (!b[i]) rt = i; } dfs(rt, 0); int tmp = st; on_path[st] = 1; while (tmp != rt) swap(a[tmp], a[fa[tmp]]), tmp = fa[tmp], on_path[tmp] = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) cir[++top] = i; sort(cir + 1, cir + top + 1, cmp); check(); if (type > 2) { puts("-1"); return 0; } if (!type) { printf("0 %d\n", dep[st]); return 0; } top = 0; get(bot[1], 1); for (int i = 1; i <= topx; i++) cir[top++] = s[i]; if (type == 2) { get(bot[2], 0); for (int i = 1; i <= topx; i++) cir[top++] = s[i]; } ans = calc(); if (ans == -1) { puts("-1"); return 0; } tmp = Top; while (!on_path[tmp]) ans += 2, tmp = fa[tmp]; ans += dep[st]; int ansx, ansy; if (type == 1) ansx = Top, ansy = bot[1]; else ansx = bot[1], ansy = bot[2]; if (ansx > ansy) swap(ansx, ansy); cout << ansx << " " << ansy << " " << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; void gg() { printf("-1\n"); exit(0); return; } int n; struct Edge { int v, nxt; } e[400010]; int tot; int first[200010]; void build(int u, int v) { e[++tot] = (Edge){v, first[u]}; first[u] = tot; return; } int a[200010], b[200010]; int fa[200010]; int dis[200010]; int pos[200010]; void dfs1(int u, int lst) { fa[u] = lst; if (lst) dis[u] = dis[lst] + 1; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != lst) dfs1(e[i].v, u); return; } bool vis[200010]; void work1() { int x = pos[1]; int res = dis[x]; while (x != 1) { vis[x] = true; swap(b[x], b[fa[x]]); x = fa[x]; } vis[1] = true; for (int i = 1; i <= n; i++) if (b[i] != i) return; printf("0 %d\n", res); exit(0); } vector<int> vec[2]; int num = 0; void getpath(int u) { if (num == 2 || (num == 1 && fa[u] != fa[vec[0][0]])) gg(); while (u) { vec[num].push_back(u); int v = 0; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u] && b[e[i].v] != e[i].v) { if (!v) v = e[i].v; else gg(); } u = v; } num++; } void dfs2(int u) { for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u]) { if (b[e[i].v] == e[i].v) dfs2(e[i].v); else getpath(e[i].v); } return; } int tmp[200010]; int ori[200010]; void work2() { int u, v, x; if (num == 1) { x = u = fa[vec[0][0]]; v = vec[0][vec[0].size() - 1]; } else { x = fa[vec[0][0]]; u = vec[0][vec[0].size() - 1]; v = vec[1][vec[1].size() - 1]; for (int i = 1; i <= vec[1].size(); i++) vec[0].push_back(vec[1][vec[1].size() - i]); } memset(tmp, -1, sizeof(tmp)); int k = 0, num = vec[0].size(); for (int i = 0; i < num; i++) { int o = vec[0][i]; tmp[o] = i; } for (int i = 1; i <= n; i++) if (tmp[i] == -1 && b[i] != i) gg(); for (int i = 0; i < num; i++) { int o = vec[0][i]; int val = (tmp[b[o]] + num - i) % num; if (i == 0) k = val; else if (k != val) gg(); } int dist = dis[u] + dis[v] - dis[x] * 2 + 1; long long ans; if (!vis[x]) { k = min(k, num - k); ans = (long long)k * dist; while (!vis[x]) ans += 2, x = fa[x]; ans += dis[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { int o = vec[0][i]; cnt += vis[o]; } if (vis[vec[0][0]]) ans = min((long long)dist * k, (long long)dist * (num - k) - 2 * cnt) + dis[pos[1]]; else ans = min((long long)dist * k - 2 * cnt, (long long)dist * (num - k)) + dis[pos[1]]; } u = ori[u]; v = ori[v]; if (u > v) swap(u, v); printf("%d %d %I64d\n", u, v, ans); return; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); u = a[u]; v = a[v]; build(u, v); build(v, u); } dfs1(1, 0); work1(); dfs2(1); work2(); return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void gg() { printf("-1\n"); exit(0); return; } int n; struct Edge { int v, nxt; } e[400010]; int tot; int first[200010]; void build(int u, int v) { e[++tot] = (Edge){v, first[u]}; first[u] = tot; return; } int a[200010], b[200010]; int fa[200010]; int dis[200010]; int pos[200010]; void dfs1(int u, int lst) { fa[u] = lst; if (lst) dis[u] = dis[lst] + 1; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != lst) dfs1(e[i].v, u); return; } bool vis[200010]; void work1() { int x = pos[1]; int res = dis[x]; while (x != 1) { vis[x] = true; swap(b[x], b[fa[x]]); x = fa[x]; } vis[1] = true; for (int i = 1; i <= n; i++) if (b[i] != i) return; printf("0 %d\n", res); exit(0); } vector<int> vec[2]; int num = 0; void getpath(int u) { if (num == 2 || (num == 1 && fa[u] != fa[vec[0][0]])) gg(); while (u) { vec[num].push_back(u); int v = 0; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u] && b[e[i].v] != e[i].v) { if (!v) v = e[i].v; else gg(); } u = v; } num++; } void dfs2(int u) { for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u]) { if (b[e[i].v] == e[i].v) dfs2(e[i].v); else getpath(e[i].v); } return; } int tmp[200010]; int ori[200010]; void work2() { int u, v, x; if (num == 1) { x = u = fa[vec[0][0]]; v = vec[0][vec[0].size() - 1]; } else { x = fa[vec[0][0]]; u = vec[0][vec[0].size() - 1]; v = vec[1][vec[1].size() - 1]; for (int i = 1; i <= vec[1].size(); i++) vec[0].push_back(vec[1][vec[1].size() - i]); } memset(tmp, -1, sizeof(tmp)); int k = 0, num = vec[0].size(); for (int i = 0; i < num; i++) { int o = vec[0][i]; tmp[o] = i; } for (int i = 1; i <= n; i++) if (tmp[i] == -1 && b[i] != i) gg(); for (int i = 0; i < num; i++) { int o = vec[0][i]; int val = (tmp[b[o]] + num - i) % num; if (i == 0) k = val; else if (k != val) gg(); } int dist = dis[u] + dis[v] - dis[x] * 2 + 1; long long ans; if (!vis[x]) { k = min(k, num - k); ans = (long long)k * dist; while (!vis[x]) ans += 2, x = fa[x]; ans += dis[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { int o = vec[0][i]; cnt += vis[o]; } if (vis[vec[0][0]]) ans = min((long long)dist * k, (long long)dist * (num - k) - 2 * cnt) + dis[pos[1]]; else ans = min((long long)dist * k - 2 * cnt, (long long)dist * (num - k)) + dis[pos[1]]; } u = ori[u]; v = ori[v]; if (u > v) swap(u, v); printf("%d %d %I64d\n", u, v, ans); return; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); u = a[u]; v = a[v]; build(u, v); build(v, u); } dfs1(1, 0); work1(); dfs2(1); work2(); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, S, T, a[200005], b[200005], fa[200005], dep[200005]; bool fl, vs[200005]; vector<int> e[200005]; int U, V, U1, cnt, ps, st1[200005], st2[200005], st3[200005], st[2][200005]; long long ans1, ans2; void dfs(int u, int f) { fa[u] = f; if (f) dep[u] = dep[f] + 1; for (int i = 0, v; i < e[u].size(); ++i) { v = e[u][i]; if (v != f) dfs(v, u); } } int ins(int u) { if (st2[st2[0]] == u) { --st2[0]; return -1; } st2[++st2[0]] = u; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (!a[i]) S = i; } for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (!b[i]) T = i; } for (int i = 1, u, v; i < n; ++i) scanf("%d %d", &u, &v), e[u].push_back(v), e[v].push_back(u); dfs(T, 0); for (int i = S; i != T; i = fa[i]) ans1 += ins(i), swap(a[i], a[fa[i]]); for (int i = 1; i <= n; ++i, fl = 0) if (!vs[i] && a[i] != b[i]) { for (int j = 0, v; j < e[i].size(); ++j) { v = e[i][j]; if (v != fa[i] && a[v] != b[v]) fl = 1; } if (fl) continue; ++cnt; if (cnt > 2) { puts("-1"); return 0; } for (int j = i; j; j = fa[j]) { if (a[j] == b[j]) break; if (vs[j]) { puts("-1"); return 0; } vs[j] = 1; st[cnt - 1][++st[cnt - 1][0]] = j; } } if (!cnt) { printf("0 %lld\n", ans1); return 0; } if (cnt < 2) U = U1 = fa[st[0][st[0][0]]], V = st[0][1]; else { U1 = fa[st[0][st[0][0]]]; U = st[0][1]; V = st[1][1]; if (U1 != fa[st[1][st[1][0]]]) { puts("-1"); return 0; } } for (int i = st[0][0]; i; --i) st1[++st1[0]] = st[0][i]; for (int i = 1; i <= st[1][0]; ++i) st1[++st1[0]] = st[1][i]; for (int i = 1; i <= st1[0]; ++i) if (a[st1[1]] == b[st1[i]]) { ps = i; break; } if (!ps) { puts("-1"); return 0; } for (int i = 1, j = ps; i <= st1[0]; ++i, j = j % st1[0] + 1) if (a[st1[i]] != b[st1[j]]) { puts("-1"); return 0; } for (int i = U1; i != T; i = fa[i]) st3[++st3[0]] = i; for (int i = st3[0]; i; --i) ans1 += ins(st3[i]); for (int i = st1[0]; i; --i) ans1 += ins(st1[i]); ++ans1; ans1 += 1ll * (st1[0] + 1) * (ps - 2) + dep[U1]; st2[0] = 0; for (int i = S; i != T; i = fa[i]) ans2 += ins(i); for (int i = st3[0]; i; --i) ans2 += ins(st3[i]); for (int i = 1; i <= st1[0]; ++i) ans2 += ins(st1[i]); ++ans2; ans2 += 1ll * (st1[0] + 1) * (st1[0] - ps) + dep[U1]; if (U > V) swap(U, V); printf("%d %d %lld\n", U, V, min(ans1, ans2)); return 0; }
### Prompt Please formulate a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, S, T, a[200005], b[200005], fa[200005], dep[200005]; bool fl, vs[200005]; vector<int> e[200005]; int U, V, U1, cnt, ps, st1[200005], st2[200005], st3[200005], st[2][200005]; long long ans1, ans2; void dfs(int u, int f) { fa[u] = f; if (f) dep[u] = dep[f] + 1; for (int i = 0, v; i < e[u].size(); ++i) { v = e[u][i]; if (v != f) dfs(v, u); } } int ins(int u) { if (st2[st2[0]] == u) { --st2[0]; return -1; } st2[++st2[0]] = u; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (!a[i]) S = i; } for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (!b[i]) T = i; } for (int i = 1, u, v; i < n; ++i) scanf("%d %d", &u, &v), e[u].push_back(v), e[v].push_back(u); dfs(T, 0); for (int i = S; i != T; i = fa[i]) ans1 += ins(i), swap(a[i], a[fa[i]]); for (int i = 1; i <= n; ++i, fl = 0) if (!vs[i] && a[i] != b[i]) { for (int j = 0, v; j < e[i].size(); ++j) { v = e[i][j]; if (v != fa[i] && a[v] != b[v]) fl = 1; } if (fl) continue; ++cnt; if (cnt > 2) { puts("-1"); return 0; } for (int j = i; j; j = fa[j]) { if (a[j] == b[j]) break; if (vs[j]) { puts("-1"); return 0; } vs[j] = 1; st[cnt - 1][++st[cnt - 1][0]] = j; } } if (!cnt) { printf("0 %lld\n", ans1); return 0; } if (cnt < 2) U = U1 = fa[st[0][st[0][0]]], V = st[0][1]; else { U1 = fa[st[0][st[0][0]]]; U = st[0][1]; V = st[1][1]; if (U1 != fa[st[1][st[1][0]]]) { puts("-1"); return 0; } } for (int i = st[0][0]; i; --i) st1[++st1[0]] = st[0][i]; for (int i = 1; i <= st[1][0]; ++i) st1[++st1[0]] = st[1][i]; for (int i = 1; i <= st1[0]; ++i) if (a[st1[1]] == b[st1[i]]) { ps = i; break; } if (!ps) { puts("-1"); return 0; } for (int i = 1, j = ps; i <= st1[0]; ++i, j = j % st1[0] + 1) if (a[st1[i]] != b[st1[j]]) { puts("-1"); return 0; } for (int i = U1; i != T; i = fa[i]) st3[++st3[0]] = i; for (int i = st3[0]; i; --i) ans1 += ins(st3[i]); for (int i = st1[0]; i; --i) ans1 += ins(st1[i]); ++ans1; ans1 += 1ll * (st1[0] + 1) * (ps - 2) + dep[U1]; st2[0] = 0; for (int i = S; i != T; i = fa[i]) ans2 += ins(i); for (int i = st3[0]; i; --i) ans2 += ins(st3[i]); for (int i = 1; i <= st1[0]; ++i) ans2 += ins(st1[i]); ++ans2; ans2 += 1ll * (st1[0] + 1) * (st1[0] - ps) + dep[U1]; if (U > V) swap(U, V); printf("%d %d %lld\n", U, V, min(ans1, ans2)); return 0; } ```
#include <bits/stdc++.h> using namespace std; int v1[200500], v2[200500], v3[200500], s, t, head[200500], cnt, is[200500], fr[200500], ct, st[200500], fg, s1, s2, s3, s4, s5, a, b, st2[200500], ct2, vl[200500], c1, ins[200500], n, fr2[200500], is2[200500], d1, is3[200500]; struct edge { int t, next; } ed[200500 * 2]; void adde(int f, int t) { ed[++cnt] = (edge){t, head[f]}; head[f] = cnt; ed[++cnt] = (edge){f, head[t]}; head[t] = cnt; } void dfs(int u, int fa) { if (!fg) st[++ct] = u; if (u == t) fg = 1; for (int i = head[u]; i; i = ed[i].next) if (ed[i].t != fa) dfs(ed[i].t, u); if (!fg) ct--; } bool check(int l, int r) { t = r; ct = 0; fg = 0; dfs(l, 0); for (int i = 1; i <= n; i++) ins[i] = 0; for (int i = 1; i <= ct; i++) ins[st[i]] = 1; for (int i = 1; i <= n; i++) if (is[i] && !ins[i]) return 0; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &v1[i]); if (!v1[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &v2[i]); if (!v2[i]) t = i; } for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), adde(a, b); dfs(s, 0); s3 = s, s4 = t; for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; int fg1 = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { fg1 = 1; is[i] = 1; for (int j = head[i]; j; j = ed[j].next) fr[ed[j].t]++; } if (!fg1) { printf("0 %d\n", ct - 1); return 0; } for (int i = 1; i <= n; i++) if (is[i] && fr[i] <= 1) vl[++c1] = i; if (c1 > 4) { printf("-1\n"); return 0; } for (int i = 1; i <= c1 && fg1 == 1; i++) for (int j = i + 1; j <= c1; j++) if (check(vl[i], vl[j])) { s1 = vl[i], s2 = vl[j]; fg1 = 2; break; } t = s2; ct = fg = 0; dfs(s1, 0); for (int i = 1; i <= ct; i++) is3[st[i]] = 1; if (fg1 == 1) { printf("-1\n"); return 0; } int v4 = 0; for (int i = 1; i <= ct; i++) if (!is[st[i]]) { if (v4) { printf("-1\n"); return 0; } v4 = st[i]; } if (!v4) { t = s1; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s1 = v4; else { t = s2; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s2 = v4; else { int st = 1; for (int i = head[s]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st = 2; if (s1 == s) s1 = v4; else s2 = v4; } if (st == 1) { int st2 = 0, st3 = (s1 == s ? s2 : s1); for (int i = head[st3]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st2 = 1; if (s1 == s) s2 = v4; else s1 = v4; } if (!st2) { printf("-1\n"); return 0; } } } } } else { t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= ct; i++) if (is3[st[i]]) { v4 = st[i]; break; } } t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; long long as = ct - 1; t = s2; ct = 0; fg = 0; dfs(s1, 0); int ct1 = 0, ct2 = 0, fg2 = -1, tp = 0; for (int i = 1; i <= ct; i++) fr2[v2[st[i]]] = i, is2[st[i]] = 1; for (int i = 1; i <= ct; i++) { if (!v3[st[i]]) continue; int nt = fr2[v3[st[i]]]; fr2[v3[st[i]]] = 0; if (!nt) { printf("-1\n"); return 0; } int st = i - nt + (i < nt ? ct : 0); if (fg2 == -1) fg2 = st, ct1 = 1; else { if (fg2 == st) ct1++; else if (fg2 == st - 1) ct2++; else if (fg2 == st + 1) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1; ct1 = 1, fg2--; } else if (fg2 == 0 && st + 1 == ct) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1, ct1 = 1, fg2 = ct - 1; } else if (st == 0 && fg2 == ct - 1) ct2++; else { printf("-1\n"); return 0; } } } for (int i = 1; i <= ct; i++) v3[st[i]] = v2[st[i]]; long long as1 = 1ll * ct1 * fg2 + 1ll * ct2 * (fg2 + 1), as2 = 1ll * ct1 * (ct - fg2) + 1ll * ct2 * (ct - fg2 - 1); if (as2 < as1) as1 = as2; as += as1; for (int i = 1; i <= n; i++) if (fr2[v2[i]]) s5 = i; v3[s5] = 0; t = s4; ct = 0; fg = 0; dfs(s5, 0); for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { printf("-1\n"); return 0; } as += ct - 1; if (s1 > s2) s1 ^= s2 ^= s1 ^= s2; printf("%d %d %lld\n", s1, s2, as); }
### Prompt In cpp, your task is to solve the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int v1[200500], v2[200500], v3[200500], s, t, head[200500], cnt, is[200500], fr[200500], ct, st[200500], fg, s1, s2, s3, s4, s5, a, b, st2[200500], ct2, vl[200500], c1, ins[200500], n, fr2[200500], is2[200500], d1, is3[200500]; struct edge { int t, next; } ed[200500 * 2]; void adde(int f, int t) { ed[++cnt] = (edge){t, head[f]}; head[f] = cnt; ed[++cnt] = (edge){f, head[t]}; head[t] = cnt; } void dfs(int u, int fa) { if (!fg) st[++ct] = u; if (u == t) fg = 1; for (int i = head[u]; i; i = ed[i].next) if (ed[i].t != fa) dfs(ed[i].t, u); if (!fg) ct--; } bool check(int l, int r) { t = r; ct = 0; fg = 0; dfs(l, 0); for (int i = 1; i <= n; i++) ins[i] = 0; for (int i = 1; i <= ct; i++) ins[st[i]] = 1; for (int i = 1; i <= n; i++) if (is[i] && !ins[i]) return 0; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &v1[i]); if (!v1[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &v2[i]); if (!v2[i]) t = i; } for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), adde(a, b); dfs(s, 0); s3 = s, s4 = t; for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; int fg1 = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { fg1 = 1; is[i] = 1; for (int j = head[i]; j; j = ed[j].next) fr[ed[j].t]++; } if (!fg1) { printf("0 %d\n", ct - 1); return 0; } for (int i = 1; i <= n; i++) if (is[i] && fr[i] <= 1) vl[++c1] = i; if (c1 > 4) { printf("-1\n"); return 0; } for (int i = 1; i <= c1 && fg1 == 1; i++) for (int j = i + 1; j <= c1; j++) if (check(vl[i], vl[j])) { s1 = vl[i], s2 = vl[j]; fg1 = 2; break; } t = s2; ct = fg = 0; dfs(s1, 0); for (int i = 1; i <= ct; i++) is3[st[i]] = 1; if (fg1 == 1) { printf("-1\n"); return 0; } int v4 = 0; for (int i = 1; i <= ct; i++) if (!is[st[i]]) { if (v4) { printf("-1\n"); return 0; } v4 = st[i]; } if (!v4) { t = s1; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s1 = v4; else { t = s2; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s2 = v4; else { int st = 1; for (int i = head[s]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st = 2; if (s1 == s) s1 = v4; else s2 = v4; } if (st == 1) { int st2 = 0, st3 = (s1 == s ? s2 : s1); for (int i = head[st3]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st2 = 1; if (s1 == s) s2 = v4; else s1 = v4; } if (!st2) { printf("-1\n"); return 0; } } } } } else { t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= ct; i++) if (is3[st[i]]) { v4 = st[i]; break; } } t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; long long as = ct - 1; t = s2; ct = 0; fg = 0; dfs(s1, 0); int ct1 = 0, ct2 = 0, fg2 = -1, tp = 0; for (int i = 1; i <= ct; i++) fr2[v2[st[i]]] = i, is2[st[i]] = 1; for (int i = 1; i <= ct; i++) { if (!v3[st[i]]) continue; int nt = fr2[v3[st[i]]]; fr2[v3[st[i]]] = 0; if (!nt) { printf("-1\n"); return 0; } int st = i - nt + (i < nt ? ct : 0); if (fg2 == -1) fg2 = st, ct1 = 1; else { if (fg2 == st) ct1++; else if (fg2 == st - 1) ct2++; else if (fg2 == st + 1) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1; ct1 = 1, fg2--; } else if (fg2 == 0 && st + 1 == ct) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1, ct1 = 1, fg2 = ct - 1; } else if (st == 0 && fg2 == ct - 1) ct2++; else { printf("-1\n"); return 0; } } } for (int i = 1; i <= ct; i++) v3[st[i]] = v2[st[i]]; long long as1 = 1ll * ct1 * fg2 + 1ll * ct2 * (fg2 + 1), as2 = 1ll * ct1 * (ct - fg2) + 1ll * ct2 * (ct - fg2 - 1); if (as2 < as1) as1 = as2; as += as1; for (int i = 1; i <= n; i++) if (fr2[v2[i]]) s5 = i; v3[s5] = 0; t = s4; ct = 0; fg = 0; dfs(s5, 0); for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { printf("-1\n"); return 0; } as += ct - 1; if (s1 > s2) s1 ^= s2 ^= s1 ^= s2; printf("%d %d %lld\n", s1, s2, as); } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, ca[N], cb[N], u[N], v[N], i, j, z, S, T, deg[N], id[N], X; long long ans; vector<int> e[N], ep; multiset<int> SS; bool b1[N]; int dad[N], dep[N]; void dfs(int x, int fa) { dep[x] = dep[fa] + 1; dad[x] = fa; for (int y : e[x]) if (y != fa) dfs(y, x); } inline vector<int> getP(int x, int y) { dfs(y, 0); vector<int> ans; for (; ans.push_back(x), x != y; x = dad[x]) ; return ans; } inline void shift(vector<int>& a, int d) { vector<int> b = vector<int>(a.begin(), a.begin() + d); a = vector<int>(a.begin() + d, a.end()); a.insert(a.end(), b.begin(), b.end()); } int dfs2(int x, int fa) { if (x == X) return !id[x]; if (b1[x]) { puts("-1"); exit(0); } for (int y : e[x]) if (y != fa) { int t = dfs2(y, x); if (t != -1) return t + !id[x]; } return -1; } int main() { scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d", ca + i), ca[i] ? 0 : S = i; for (i = 1; i <= n; ++i) scanf("%d", cb + i), cb[i] ? 0 : T = i; for (i = 1; i < n; ++i) scanf("%d%d", u + i, v + i), e[u[i]].push_back(v[i]), e[v[i]].push_back(u[i]); auto zz = getP(S, T); for (i = 0; i + 1 < zz.size(); ++i) swap(ca[zz[i]], ca[zz[i + 1]]), ++ans; for (i = 0; i < zz.size(); ++i) id[zz[i]] = i + 1; for (i = 1; i <= n; ++i) b1[i] = ca[i] != cb[i]; for (i = 1; i < n; ++i) if (b1[u[i]] && b1[v[i]]) ++deg[u[i]], ++deg[v[i]]; for (i = 1; i <= n; ++i) if (b1[i] && deg[i] < 2) for (int x = 2 - deg[i]; x--;) SS.insert(i); if (SS.empty()) { printf("0 %lld\n", ans); return 0; } dfs(T, 0); int mn = N, mnid = 0; for (i = 1; i <= n; ++i) if (b1[i] && dep[i] < mn) mn = dep[i], mnid = i; if (SS.size() == 2) { if (deg[mnid] > 1) { puts("-1"); return 0; } X = dad[mnid]; ep = {X, *SS.begin() ^ *SS.rbegin() ^ mnid}; } else if (SS.size() == 4) { for (i = 1; i <= n; ++i) if (!b1[i]) { int ct = 0; for (int j : e[i]) ct += b1[j] && deg[j] < 2; if (ct == 2) break; } if (i > n) { puts("-1"); return 0; } X = i; if (dep[X] >= dep[mnid]) { puts("-1"); return 0; } for (int j : e[i]) if (b1[j] && deg[j] < 2) SS.erase(SS.find(j)); ep = {*SS.begin(), *SS.rbegin()}; } else { puts("-1"); return 0; } auto p0 = getP(ep[0], ep[1]), pp0 = p0; p0.erase(find(p0.begin(), p0.end(), X)); auto p1 = p0, p2 = p0; for (int& x : p1) x = ca[x]; for (int& y : p2) y = cb[y]; for (i = 0; i < p1.size() && p1[i] != p2[0]; ++i) ; if (i == p1.size()) { puts("-1"); return 0; } shift(p1, i); if (p1 != p2) { puts("-1"); return 0; } for (int x : p0) z += id[x] > 0; if (z < 1) { ans += dfs2(T, 0) * 2; ans += 1ll * (p0.size() + 1) * min(int(p0.size() - i), i); } else { p0 = pp0; p0.push_back(p0[0]); long long v1 = 1ll * (p0.size() - 1) * i, v2 = 1ll * (p0.size() - 1) * (p1.size() - i); if (v1) for (j = 0; j + 1 < p0.size(); ++j) v1 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] - 1 == id[p0[j + 1]]) * 2; if (v2) for (j = 0; j + 1 < p0.size(); ++j) v2 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] + 1 == id[p0[j + 1]]) * 2; ans += min(v1, v2); } sort(ep.begin(), ep.end()); printf("%d %d %lld\n", ep[0], ep[1], ans); return 0; }
### Prompt In Cpp, your task is to solve the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, ca[N], cb[N], u[N], v[N], i, j, z, S, T, deg[N], id[N], X; long long ans; vector<int> e[N], ep; multiset<int> SS; bool b1[N]; int dad[N], dep[N]; void dfs(int x, int fa) { dep[x] = dep[fa] + 1; dad[x] = fa; for (int y : e[x]) if (y != fa) dfs(y, x); } inline vector<int> getP(int x, int y) { dfs(y, 0); vector<int> ans; for (; ans.push_back(x), x != y; x = dad[x]) ; return ans; } inline void shift(vector<int>& a, int d) { vector<int> b = vector<int>(a.begin(), a.begin() + d); a = vector<int>(a.begin() + d, a.end()); a.insert(a.end(), b.begin(), b.end()); } int dfs2(int x, int fa) { if (x == X) return !id[x]; if (b1[x]) { puts("-1"); exit(0); } for (int y : e[x]) if (y != fa) { int t = dfs2(y, x); if (t != -1) return t + !id[x]; } return -1; } int main() { scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d", ca + i), ca[i] ? 0 : S = i; for (i = 1; i <= n; ++i) scanf("%d", cb + i), cb[i] ? 0 : T = i; for (i = 1; i < n; ++i) scanf("%d%d", u + i, v + i), e[u[i]].push_back(v[i]), e[v[i]].push_back(u[i]); auto zz = getP(S, T); for (i = 0; i + 1 < zz.size(); ++i) swap(ca[zz[i]], ca[zz[i + 1]]), ++ans; for (i = 0; i < zz.size(); ++i) id[zz[i]] = i + 1; for (i = 1; i <= n; ++i) b1[i] = ca[i] != cb[i]; for (i = 1; i < n; ++i) if (b1[u[i]] && b1[v[i]]) ++deg[u[i]], ++deg[v[i]]; for (i = 1; i <= n; ++i) if (b1[i] && deg[i] < 2) for (int x = 2 - deg[i]; x--;) SS.insert(i); if (SS.empty()) { printf("0 %lld\n", ans); return 0; } dfs(T, 0); int mn = N, mnid = 0; for (i = 1; i <= n; ++i) if (b1[i] && dep[i] < mn) mn = dep[i], mnid = i; if (SS.size() == 2) { if (deg[mnid] > 1) { puts("-1"); return 0; } X = dad[mnid]; ep = {X, *SS.begin() ^ *SS.rbegin() ^ mnid}; } else if (SS.size() == 4) { for (i = 1; i <= n; ++i) if (!b1[i]) { int ct = 0; for (int j : e[i]) ct += b1[j] && deg[j] < 2; if (ct == 2) break; } if (i > n) { puts("-1"); return 0; } X = i; if (dep[X] >= dep[mnid]) { puts("-1"); return 0; } for (int j : e[i]) if (b1[j] && deg[j] < 2) SS.erase(SS.find(j)); ep = {*SS.begin(), *SS.rbegin()}; } else { puts("-1"); return 0; } auto p0 = getP(ep[0], ep[1]), pp0 = p0; p0.erase(find(p0.begin(), p0.end(), X)); auto p1 = p0, p2 = p0; for (int& x : p1) x = ca[x]; for (int& y : p2) y = cb[y]; for (i = 0; i < p1.size() && p1[i] != p2[0]; ++i) ; if (i == p1.size()) { puts("-1"); return 0; } shift(p1, i); if (p1 != p2) { puts("-1"); return 0; } for (int x : p0) z += id[x] > 0; if (z < 1) { ans += dfs2(T, 0) * 2; ans += 1ll * (p0.size() + 1) * min(int(p0.size() - i), i); } else { p0 = pp0; p0.push_back(p0[0]); long long v1 = 1ll * (p0.size() - 1) * i, v2 = 1ll * (p0.size() - 1) * (p1.size() - i); if (v1) for (j = 0; j + 1 < p0.size(); ++j) v1 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] - 1 == id[p0[j + 1]]) * 2; if (v2) for (j = 0; j + 1 < p0.size(); ++j) v2 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] + 1 == id[p0[j + 1]]) * 2; ans += min(v1, v2); } sort(ep.begin(), ep.end()); printf("%d %d %lld\n", ep[0], ep[1], ans); return 0; } ```
#include <bits/stdc++.h> int head[262144], last[524288], to[524288], cnt = 0; void add(int u, int v) { cnt++; last[cnt] = head[u]; head[u] = cnt; to[cnt] = v; } int d[262144], fa[262144], d2[262144], fa2[262144]; void dfs(int u, int f) { d[u] = d[f] + 1; fa[u] = f; for (int i = head[u]; i; i = last[i]) { int v = to[i]; if (v == f) { continue; } dfs(v, u); } } int a[262144], b[262144]; int x[262144], num = 0; int dfs2(int u, int f) { d2[u] = d2[f] + 1; fa2[u] = f; int ans; if (b[u] == a[u]) { ans = 2; } else { ans = 1; } for (int i = head[u]; i; i = last[i]) { int v = to[i]; if (v == f) { continue; } int ans2 = dfs2(v, u); if (ans2 < 0) { return -1; } if (ans2) { ans--; if (ans < 0) { return -1; } } } if (ans && a[u] != b[u]) { x[num] = u; num++; } return a[u] != b[u]; } int aa[262144], bb[262144]; int main() { int n; scanf("%d", &n); int root, root2; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (a[i] == 0) { root = i; } } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (b[i] == 0) { root2 = i; } } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } d[0] = -1; d2[0] = -1; dfs(root, 0); int now = 0; for (int i = root2; i; i = fa[i]) { int t = a[i]; a[i] = now; now = t; } if (dfs2(root2, 0) < 0) { printf("-1\n"); return 0; } if (num > 2) { printf("-1\n"); return 0; } if (num == 0) { printf("0 %d\n", d[root2]); return 0; } int u, v, dd; if (num == 1) { u = x[0]; for (int i = u;; i = fa2[i]) { if (a[i] == b[i]) { v = i; break; } } dd = d2[u] - d2[v]; if (u < v) { for (int i = u; i != v; i = fa2[i]) { aa[d2[u] - d2[i]] = a[i]; bb[d2[u] - d2[i]] = b[i]; } } else { for (int i = u; i != v; i = fa2[i]) { aa[d2[i] - d2[v] - 1] = a[i]; bb[d2[i] - d2[v] - 1] = b[i]; } int t = u; u = v; v = t; } } else { u = x[0]; v = x[1]; if (u > v) { int t = u; u = v; v = t; } int root3; for (int i = u;; i = fa2[i]) { aa[d2[u] - d2[i]] = a[i]; bb[d2[u] - d2[i]] = b[i]; if (a[i] == b[i]) { root3 = i; break; } } dd = d2[u] + d2[v] - d2[root3] - d2[root3]; for (int i = v; i != root3; i = fa2[i]) { if (d2[i] <= d2[root3]) { printf("-1\n"); return 0; } aa[d2[i] + d2[u] - d2[root3] - d2[root3] - 1] = a[i]; bb[d2[i] + d2[u] - d2[root3] - d2[root3] - 1] = b[i]; if (a[i] == b[i]) { printf("-1\n"); return 0; } } } int dd1 = 0, dd2 = 0; for (int i = 1; i < dd; i++) { if (bb[i] == aa[0]) { dd1 = i; dd2 = dd - i; break; } } for (int i = 0; i < dd; i++) { int j = i + dd1; if (j >= dd) { j -= dd; } if (bb[j] != aa[i]) { printf("-1\n"); return 0; } } printf("%d %d ", u, v); long long ans1 = (long long)(dd + 1) * (dd1 - 1) + d[u] + d2[v] + 1; long long ans2 = (long long)(dd + 1) * (dd2 - 1) + d[v] + d2[u] + 1; if (ans2 < ans1) { ans1 = ans2; } printf("%lld\n", ans1); return 0; }
### Prompt In CPP, your task is to solve the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> int head[262144], last[524288], to[524288], cnt = 0; void add(int u, int v) { cnt++; last[cnt] = head[u]; head[u] = cnt; to[cnt] = v; } int d[262144], fa[262144], d2[262144], fa2[262144]; void dfs(int u, int f) { d[u] = d[f] + 1; fa[u] = f; for (int i = head[u]; i; i = last[i]) { int v = to[i]; if (v == f) { continue; } dfs(v, u); } } int a[262144], b[262144]; int x[262144], num = 0; int dfs2(int u, int f) { d2[u] = d2[f] + 1; fa2[u] = f; int ans; if (b[u] == a[u]) { ans = 2; } else { ans = 1; } for (int i = head[u]; i; i = last[i]) { int v = to[i]; if (v == f) { continue; } int ans2 = dfs2(v, u); if (ans2 < 0) { return -1; } if (ans2) { ans--; if (ans < 0) { return -1; } } } if (ans && a[u] != b[u]) { x[num] = u; num++; } return a[u] != b[u]; } int aa[262144], bb[262144]; int main() { int n; scanf("%d", &n); int root, root2; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (a[i] == 0) { root = i; } } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (b[i] == 0) { root2 = i; } } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } d[0] = -1; d2[0] = -1; dfs(root, 0); int now = 0; for (int i = root2; i; i = fa[i]) { int t = a[i]; a[i] = now; now = t; } if (dfs2(root2, 0) < 0) { printf("-1\n"); return 0; } if (num > 2) { printf("-1\n"); return 0; } if (num == 0) { printf("0 %d\n", d[root2]); return 0; } int u, v, dd; if (num == 1) { u = x[0]; for (int i = u;; i = fa2[i]) { if (a[i] == b[i]) { v = i; break; } } dd = d2[u] - d2[v]; if (u < v) { for (int i = u; i != v; i = fa2[i]) { aa[d2[u] - d2[i]] = a[i]; bb[d2[u] - d2[i]] = b[i]; } } else { for (int i = u; i != v; i = fa2[i]) { aa[d2[i] - d2[v] - 1] = a[i]; bb[d2[i] - d2[v] - 1] = b[i]; } int t = u; u = v; v = t; } } else { u = x[0]; v = x[1]; if (u > v) { int t = u; u = v; v = t; } int root3; for (int i = u;; i = fa2[i]) { aa[d2[u] - d2[i]] = a[i]; bb[d2[u] - d2[i]] = b[i]; if (a[i] == b[i]) { root3 = i; break; } } dd = d2[u] + d2[v] - d2[root3] - d2[root3]; for (int i = v; i != root3; i = fa2[i]) { if (d2[i] <= d2[root3]) { printf("-1\n"); return 0; } aa[d2[i] + d2[u] - d2[root3] - d2[root3] - 1] = a[i]; bb[d2[i] + d2[u] - d2[root3] - d2[root3] - 1] = b[i]; if (a[i] == b[i]) { printf("-1\n"); return 0; } } } int dd1 = 0, dd2 = 0; for (int i = 1; i < dd; i++) { if (bb[i] == aa[0]) { dd1 = i; dd2 = dd - i; break; } } for (int i = 0; i < dd; i++) { int j = i + dd1; if (j >= dd) { j -= dd; } if (bb[j] != aa[i]) { printf("-1\n"); return 0; } } printf("%d %d ", u, v); long long ans1 = (long long)(dd + 1) * (dd1 - 1) + d[u] + d2[v] + 1; long long ans2 = (long long)(dd + 1) * (dd2 - 1) + d[v] + d2[u] + 1; if (ans2 < ans1) { ans1 = ans2; } printf("%lld\n", ans1); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> lk[maxn]; int fa[maxn], dep[maxn], a[maxn], b[maxn], n; void dfs(int now, int pre) { fa[now] = pre; dep[now] = dep[pre] + 1; for (auto p : lk[now]) if (p != pre) dfs(p, now); } vector<int> cir; int rt, lp, lq; bool find_circle() { cir.clear(); static bool vis[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; int u, v; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[rt]) return 0; lp = p, lq = q; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); lk[u].push_back(v), lk[v].push_back(u); } int pa = find(a + 1, a + n + 1, 0) - a, pb = find(b + 1, b + n + 1, 0) - b; dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; for (int i = 1; i < len; i++) if (b[cir[(i + gap) % len]] != a[cir[i]]) { printf("-1\n"); return 0; } static bool vis[maxn]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { if (vis[cir.back()]) reverse(cir.begin(), cir.end()), gap = len - gap; int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> lk[maxn]; int fa[maxn], dep[maxn], a[maxn], b[maxn], n; void dfs(int now, int pre) { fa[now] = pre; dep[now] = dep[pre] + 1; for (auto p : lk[now]) if (p != pre) dfs(p, now); } vector<int> cir; int rt, lp, lq; bool find_circle() { cir.clear(); static bool vis[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; int u, v; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[rt]) return 0; lp = p, lq = q; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); lk[u].push_back(v), lk[v].push_back(u); } int pa = find(a + 1, a + n + 1, 0) - a, pb = find(b + 1, b + n + 1, 0) - b; dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; for (int i = 1; i < len; i++) if (b[cir[(i + gap) % len]] != a[cir[i]]) { printf("-1\n"); return 0; } static bool vis[maxn]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { if (vis[cir.back()]) reverse(cir.begin(), cir.end()), gap = len - gap; int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 7; long long val; bool vas, fl[N], ft[N], gt[N], qt[N]; int n, p1[N], p2[N], p3[N], og[N], vac[N], st[N << 2]; vector<int> v[N]; inline int read() { int num = 0; char g = getchar(); while (g < 48 || 57 < g) g = getchar(); while (47 < g && g < 58) num = (num << 1) + (num << 3) + g - 48, g = getchar(); return num; } inline void calc(int u, int t) { st[++st[0]] = u; if (u == t) { for (int i = 1; i <= st[0]; i++) qt[st[i]] = 1; for (int i = 1; i < st[0]; i++) swap(p1[st[i]], p1[st[i + 1]]), val++, vac[st[i + 1]] = st[i]; st[0]--; return; } for (int i = 0; i < v[u].size(); i++) if (st[0] == 1 || st[st[0] - 1] != v[u][i]) calc(v[u][i], t); st[0]--; } inline pair<int, int> getans() { int a = 0, b = 0; for (int i = 1; i <= n; i++) if (!ft[i] && fl[i]) a = i, b = i; ft[a] = ft[b] = 1; while (1) { for (int i = 0; i < v[a].size(); i++) if (!ft[v[a][i]] && fl[v[a][i]]) { a = v[a][i]; break; } if (ft[a]) break; ft[a] = 1; } swap(a, b); while (1) { for (int i = 0; i < v[a].size(); i++) if (!ft[v[a][i]] && fl[v[a][i]]) { a = v[a][i]; break; } if (ft[a]) break; ft[a] = 1; } return make_pair(a, b); } inline bool check() { for (int i = 1; i <= n; i++) if (p1[i] != p2[i]) return 0; return 1; } inline long long getval() { memcpy(p3, p1, sizeof(p3)); int a = 0, b = 0; long long sum = 0; for (int i = 1; i <= st[0] * 2; i++) { int x = st[i]; if (p1[x] == 0) a = i, b = 0; if (p2[x] == 0) b = i; if (a > 0 && b > 0) break; } for (int i = a; i < b; i++) swap(p3[st[i]], p3[st[i + 1]]), sum++; int rt = 0, len = 0, pos = 0; for (int i = 1; i <= st[0]; i++) if (p3[st[i]]) og[len++] = st[i]; for (int i = 0; i < len; i++) if (p2[og[i]] == p3[og[0]]) pos = i; for (int i = 0; i < len; i++) if (p2[og[(i + pos) % len]] != p3[og[i]]) return -1; if ((len - pos) % len > 0) { for (int i = 1; i <= st[0]; i++) if (vac[st[i]] == st[i + 1]) sum -= 2; } else { for (int i = a; i < b; i++) if (vac[st[i]] == st[i + 1]) sum -= 2; } return 1ll * ((len - pos) % len) * (len + 1) + sum; } inline void solvex(int u) { gt[u] = 1; st[++st[0]] = u; for (int i = 0; i < v[u].size(); i++) { int x = v[u][i]; if (!gt[x] && fl[x]) { solvex(x); return; } } } inline void solvey(int u, int fa, int c) { if (vas) return; if (fl[u]) { vas = 1; if (vac[fa] != u) c -= 2; val += c, p1[fa] = p2[fa] = 0, fl[fa] = 1; return; } for (int i = 0; i < v[u].size(); i++) { int x = v[u][i]; if (x == fa) continue; if (vac[u] != x) solvey(x, u, c + 2); else solvey(x, u, c); } } inline void solvez(int u, int fa) { if (fl[u]) { p2[u] = 0; return; } for (int i = 0; i < v[u].size(); i++) { int x = v[u][i]; if (x == fa) continue; solvez(x, u); } } int main() { n = read(); int u, t; for (int i = 1; i <= n; i++) p1[i] = read(); for (int i = 1; i <= n; i++) p2[i] = read(); for (int i = 1; i < n; i++) u = read(), t = read(), v[u].push_back(t), v[t].push_back(u); for (int i = 1; i <= n; i++) if (p1[i] == 0) u = i; for (int i = 1; i <= n; i++) if (p2[i] == 0) t = i; calc(u, t); if (check()) { cout << 0 << " " << val << endl; return 0; } int pos = 0; for (int i = 1; i <= n; i++) if (p1[i] != p2[i] || i == pos) fl[i] = 1; solvey(t, 0, 0); pair<int, int> f1 = getans(), f2 = getans(); if (f2.first || f2.second) { cout << -1 << endl; return 0; } memset(gt, 0, sizeof(gt)), solvex(f1.first); for (int i = 1; i <= st[0] + st[0]; i++) st[i + st[0] + st[0]] = st[i + st[0]] = st[i]; long long v1 = getval(); for (int i = 1; i <= st[0] / 2; i++) swap(st[i], st[st[0] - i + 1]); for (int i = 1; i <= st[0] + st[0]; i++) st[i + st[0] + st[0]] = st[i + st[0]] = st[i]; long long v2 = getval(); if (v1 == -1 && v2 == -1) { cout << -1 << endl; return 0; } val += min(v1, v2); if (f1.first > f1.second) swap(f1.first, f1.second); cout << f1.first << " " << f1.second << " " << val << endl; }
### Prompt Develop a solution in Cpp to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 7; long long val; bool vas, fl[N], ft[N], gt[N], qt[N]; int n, p1[N], p2[N], p3[N], og[N], vac[N], st[N << 2]; vector<int> v[N]; inline int read() { int num = 0; char g = getchar(); while (g < 48 || 57 < g) g = getchar(); while (47 < g && g < 58) num = (num << 1) + (num << 3) + g - 48, g = getchar(); return num; } inline void calc(int u, int t) { st[++st[0]] = u; if (u == t) { for (int i = 1; i <= st[0]; i++) qt[st[i]] = 1; for (int i = 1; i < st[0]; i++) swap(p1[st[i]], p1[st[i + 1]]), val++, vac[st[i + 1]] = st[i]; st[0]--; return; } for (int i = 0; i < v[u].size(); i++) if (st[0] == 1 || st[st[0] - 1] != v[u][i]) calc(v[u][i], t); st[0]--; } inline pair<int, int> getans() { int a = 0, b = 0; for (int i = 1; i <= n; i++) if (!ft[i] && fl[i]) a = i, b = i; ft[a] = ft[b] = 1; while (1) { for (int i = 0; i < v[a].size(); i++) if (!ft[v[a][i]] && fl[v[a][i]]) { a = v[a][i]; break; } if (ft[a]) break; ft[a] = 1; } swap(a, b); while (1) { for (int i = 0; i < v[a].size(); i++) if (!ft[v[a][i]] && fl[v[a][i]]) { a = v[a][i]; break; } if (ft[a]) break; ft[a] = 1; } return make_pair(a, b); } inline bool check() { for (int i = 1; i <= n; i++) if (p1[i] != p2[i]) return 0; return 1; } inline long long getval() { memcpy(p3, p1, sizeof(p3)); int a = 0, b = 0; long long sum = 0; for (int i = 1; i <= st[0] * 2; i++) { int x = st[i]; if (p1[x] == 0) a = i, b = 0; if (p2[x] == 0) b = i; if (a > 0 && b > 0) break; } for (int i = a; i < b; i++) swap(p3[st[i]], p3[st[i + 1]]), sum++; int rt = 0, len = 0, pos = 0; for (int i = 1; i <= st[0]; i++) if (p3[st[i]]) og[len++] = st[i]; for (int i = 0; i < len; i++) if (p2[og[i]] == p3[og[0]]) pos = i; for (int i = 0; i < len; i++) if (p2[og[(i + pos) % len]] != p3[og[i]]) return -1; if ((len - pos) % len > 0) { for (int i = 1; i <= st[0]; i++) if (vac[st[i]] == st[i + 1]) sum -= 2; } else { for (int i = a; i < b; i++) if (vac[st[i]] == st[i + 1]) sum -= 2; } return 1ll * ((len - pos) % len) * (len + 1) + sum; } inline void solvex(int u) { gt[u] = 1; st[++st[0]] = u; for (int i = 0; i < v[u].size(); i++) { int x = v[u][i]; if (!gt[x] && fl[x]) { solvex(x); return; } } } inline void solvey(int u, int fa, int c) { if (vas) return; if (fl[u]) { vas = 1; if (vac[fa] != u) c -= 2; val += c, p1[fa] = p2[fa] = 0, fl[fa] = 1; return; } for (int i = 0; i < v[u].size(); i++) { int x = v[u][i]; if (x == fa) continue; if (vac[u] != x) solvey(x, u, c + 2); else solvey(x, u, c); } } inline void solvez(int u, int fa) { if (fl[u]) { p2[u] = 0; return; } for (int i = 0; i < v[u].size(); i++) { int x = v[u][i]; if (x == fa) continue; solvez(x, u); } } int main() { n = read(); int u, t; for (int i = 1; i <= n; i++) p1[i] = read(); for (int i = 1; i <= n; i++) p2[i] = read(); for (int i = 1; i < n; i++) u = read(), t = read(), v[u].push_back(t), v[t].push_back(u); for (int i = 1; i <= n; i++) if (p1[i] == 0) u = i; for (int i = 1; i <= n; i++) if (p2[i] == 0) t = i; calc(u, t); if (check()) { cout << 0 << " " << val << endl; return 0; } int pos = 0; for (int i = 1; i <= n; i++) if (p1[i] != p2[i] || i == pos) fl[i] = 1; solvey(t, 0, 0); pair<int, int> f1 = getans(), f2 = getans(); if (f2.first || f2.second) { cout << -1 << endl; return 0; } memset(gt, 0, sizeof(gt)), solvex(f1.first); for (int i = 1; i <= st[0] + st[0]; i++) st[i + st[0] + st[0]] = st[i + st[0]] = st[i]; long long v1 = getval(); for (int i = 1; i <= st[0] / 2; i++) swap(st[i], st[st[0] - i + 1]); for (int i = 1; i <= st[0] + st[0]; i++) st[i + st[0] + st[0]] = st[i + st[0]] = st[i]; long long v2 = getval(); if (v1 == -1 && v2 == -1) { cout << -1 << endl; return 0; } val += min(v1, v2); if (f1.first > f1.second) swap(f1.first, f1.second); cout << f1.first << " " << f1.second << " " << val << endl; } ```
#include <bits/stdc++.h> int fr[200010], ne[400010], v[400010], bs = 0; void addb(int a, int b) { v[bs] = b; ne[bs] = fr[a]; fr[a] = bs++; } int st[200010], en[200010], fa[200010], sw[200010], ew[200010], sd[200010]; void dfs(int u, int f) { fa[u] = f; if (f) sd[u] = sd[f] + 1; else sd[u] = 0; for (int i = fr[u]; i != -1; i = ne[i]) { if (v[i] != f) dfs(v[i], u); } } int sz[200010]; int check0(int n) { dfs(ew[0], 0); for (int i = 1; i <= n; i++) sz[i] = st[i]; int u = sw[0], s = 0; while (u != ew[0]) { int f = fa[u]; int t = sz[u]; sz[u] = sz[f]; sz[f] = t; u = f; s += 1; } for (int i = 1; i <= n; i++) { if (sz[i] != en[i]) return -1; } return s; } struct SJd { int u, z; SJd() {} SJd(int U, int Z) { u = U; z = Z; } }; SJd px[200010]; int cmp(const void* a, const void* b) { return ((SJd*)a)->z - ((SJd*)b)->z; } int wz[200010], sa[200010], sb[200010]; long long check(int n, int m, int ss[200010], int ux, int uy) { int wx, wy; for (int i = 0; i < n; i++) wz[i] = -1; for (int i = 0, x = 0; i < m; i++) { if (ss[i] != ux) wz[st[ss[i]]] = x; else wx = i; if (ss[i] == uy) wy = i; if (ss[i] != ux) x += 1; } int cc, cz = -1, bb; if (wy > wx) cc = wy - wx, bb = -1; else cc = wx - wy, bb = 1; for (int i = 0, x = 0; i < m; i++) { if (ss[i] == ux) continue; int j = wz[en[ss[i]]]; if (j == -1) return -1; int z = (j - x + m - 1) % (m - 1); if (cz != -1 && z != cz) return -1; cz = z; x += 1; } long long rt1 = 1ll * cz * m - cc * bb; long long rt2 = 1ll * (m - 1 - cz) * m + cc * bb; if (rt2 < rt1) rt1 = rt2; return rt1 + sd[ux]; } int caldis(int x, int y) { int rt = 0; while (sd[x] > sd[y]) x = fa[x], rt += 1; while (sd[x] < sd[y]) y = fa[y], rt += 1; while (x != y) { x = fa[x]; y = fa[y]; rt += 2; } return rt; } int xl[200010]; bool bk[200010]; int main() { int n, m = 0; long long jg; scanf("%d", &n); for (int i = 1; i <= n; i++) { fr[i] = -1; scanf("%d", &st[i]); sw[st[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &en[i]); ew[en[i]] = i; } for (int i = 0; i < n - 1; i++) { int a, b; scanf("%d%d", &a, &b); addb(a, b); addb(b, a); } if ((jg = check0(n)) >= 0) { printf("0 %lld", jg); return 0; } dfs(sw[0], 0); int u = ew[0]; while (u != sw[0]) { int f = fa[u], t = en[u]; en[u] = en[f]; en[f] = t; u = f; } for (int i = 1; i <= n; i++) { if (st[i] != en[i]) px[m++] = SJd(i, sd[i]); } qsort(px, m, sizeof(SJd), cmp); int sm = 0; for (int i = 0; i < m; i++) { if (px[i].z == px[0].z) sm += 1; } if (sm > 2) { printf("-1"); return 0; } if (sm == 1) { int tp = px[0].u, la = tp, k = 0; for (int i = 0; i < n; i++) wz[i] = -1; for (int i = 0; i < m; i++) wz[st[px[i].u]] = i; for (int i = 1; i < m; i++) { int t = px[i].u; if (fa[t] != la) { printf("-1"); return 0; } la = t; } xl[k++] = fa[tp]; for (int i = 0; i < m; i++) xl[k++] = px[i].u; for (int i = 0; i < k; i++) bk[xl[i]] = true; int ss = 0, u = ew[0]; while (u && !bk[u]) { u = fa[u]; ss += 1; } if (u == 0) u = fa[tp], ss = caldis(ew[0], fa[tp]); jg = check(n, k, xl, fa[tp], u); if (jg == -1) printf("-1"); else { if (fa[tp] < la) printf("%d %d %lld", fa[tp], la, jg + ss); else printf("%d %d %lld", la, fa[tp], jg + ss); } } else { int tx = px[0].u, ty = px[1].u, lx = tx, ly = ty; if (fa[tx] == 0 || fa[ty] == 0 || fa[tx] != fa[ty]) { printf("-1"); return 0; } int a = 0, b = 0; sa[a++] = lx; sb[b++] = ly; for (int i = 2; i < m; i++) { int t = px[i].u; if (fa[t] == lx) { sa[a++] = t; lx = t; } else if (fa[t] == ly) { sb[b++] = t; ly = t; } else { printf("-1"); return 0; } } int k = 0; for (int i = b - 1; i >= 0; i--) xl[k++] = sb[i]; xl[k++] = fa[tx]; for (int i = 0; i < a; i++) xl[k++] = sa[i]; for (int i = 0; i < k; i++) bk[xl[i]] = true; int ss = 0, u = ew[0]; while (u && !bk[u]) { u = fa[u]; ss += 1; } if (u == 0) u = fa[tx], ss = caldis(ew[0], fa[tx]); jg = check(n, k, xl, fa[tx], u); if (jg == -1) printf("-1"); else { if (lx < ly) printf("%d %d %lld", lx, ly, jg + ss); else printf("%d %d %lld", ly, lx, jg + ss); } } return 0; }
### Prompt Create a solution in Cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> int fr[200010], ne[400010], v[400010], bs = 0; void addb(int a, int b) { v[bs] = b; ne[bs] = fr[a]; fr[a] = bs++; } int st[200010], en[200010], fa[200010], sw[200010], ew[200010], sd[200010]; void dfs(int u, int f) { fa[u] = f; if (f) sd[u] = sd[f] + 1; else sd[u] = 0; for (int i = fr[u]; i != -1; i = ne[i]) { if (v[i] != f) dfs(v[i], u); } } int sz[200010]; int check0(int n) { dfs(ew[0], 0); for (int i = 1; i <= n; i++) sz[i] = st[i]; int u = sw[0], s = 0; while (u != ew[0]) { int f = fa[u]; int t = sz[u]; sz[u] = sz[f]; sz[f] = t; u = f; s += 1; } for (int i = 1; i <= n; i++) { if (sz[i] != en[i]) return -1; } return s; } struct SJd { int u, z; SJd() {} SJd(int U, int Z) { u = U; z = Z; } }; SJd px[200010]; int cmp(const void* a, const void* b) { return ((SJd*)a)->z - ((SJd*)b)->z; } int wz[200010], sa[200010], sb[200010]; long long check(int n, int m, int ss[200010], int ux, int uy) { int wx, wy; for (int i = 0; i < n; i++) wz[i] = -1; for (int i = 0, x = 0; i < m; i++) { if (ss[i] != ux) wz[st[ss[i]]] = x; else wx = i; if (ss[i] == uy) wy = i; if (ss[i] != ux) x += 1; } int cc, cz = -1, bb; if (wy > wx) cc = wy - wx, bb = -1; else cc = wx - wy, bb = 1; for (int i = 0, x = 0; i < m; i++) { if (ss[i] == ux) continue; int j = wz[en[ss[i]]]; if (j == -1) return -1; int z = (j - x + m - 1) % (m - 1); if (cz != -1 && z != cz) return -1; cz = z; x += 1; } long long rt1 = 1ll * cz * m - cc * bb; long long rt2 = 1ll * (m - 1 - cz) * m + cc * bb; if (rt2 < rt1) rt1 = rt2; return rt1 + sd[ux]; } int caldis(int x, int y) { int rt = 0; while (sd[x] > sd[y]) x = fa[x], rt += 1; while (sd[x] < sd[y]) y = fa[y], rt += 1; while (x != y) { x = fa[x]; y = fa[y]; rt += 2; } return rt; } int xl[200010]; bool bk[200010]; int main() { int n, m = 0; long long jg; scanf("%d", &n); for (int i = 1; i <= n; i++) { fr[i] = -1; scanf("%d", &st[i]); sw[st[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &en[i]); ew[en[i]] = i; } for (int i = 0; i < n - 1; i++) { int a, b; scanf("%d%d", &a, &b); addb(a, b); addb(b, a); } if ((jg = check0(n)) >= 0) { printf("0 %lld", jg); return 0; } dfs(sw[0], 0); int u = ew[0]; while (u != sw[0]) { int f = fa[u], t = en[u]; en[u] = en[f]; en[f] = t; u = f; } for (int i = 1; i <= n; i++) { if (st[i] != en[i]) px[m++] = SJd(i, sd[i]); } qsort(px, m, sizeof(SJd), cmp); int sm = 0; for (int i = 0; i < m; i++) { if (px[i].z == px[0].z) sm += 1; } if (sm > 2) { printf("-1"); return 0; } if (sm == 1) { int tp = px[0].u, la = tp, k = 0; for (int i = 0; i < n; i++) wz[i] = -1; for (int i = 0; i < m; i++) wz[st[px[i].u]] = i; for (int i = 1; i < m; i++) { int t = px[i].u; if (fa[t] != la) { printf("-1"); return 0; } la = t; } xl[k++] = fa[tp]; for (int i = 0; i < m; i++) xl[k++] = px[i].u; for (int i = 0; i < k; i++) bk[xl[i]] = true; int ss = 0, u = ew[0]; while (u && !bk[u]) { u = fa[u]; ss += 1; } if (u == 0) u = fa[tp], ss = caldis(ew[0], fa[tp]); jg = check(n, k, xl, fa[tp], u); if (jg == -1) printf("-1"); else { if (fa[tp] < la) printf("%d %d %lld", fa[tp], la, jg + ss); else printf("%d %d %lld", la, fa[tp], jg + ss); } } else { int tx = px[0].u, ty = px[1].u, lx = tx, ly = ty; if (fa[tx] == 0 || fa[ty] == 0 || fa[tx] != fa[ty]) { printf("-1"); return 0; } int a = 0, b = 0; sa[a++] = lx; sb[b++] = ly; for (int i = 2; i < m; i++) { int t = px[i].u; if (fa[t] == lx) { sa[a++] = t; lx = t; } else if (fa[t] == ly) { sb[b++] = t; ly = t; } else { printf("-1"); return 0; } } int k = 0; for (int i = b - 1; i >= 0; i--) xl[k++] = sb[i]; xl[k++] = fa[tx]; for (int i = 0; i < a; i++) xl[k++] = sa[i]; for (int i = 0; i < k; i++) bk[xl[i]] = true; int ss = 0, u = ew[0]; while (u && !bk[u]) { u = fa[u]; ss += 1; } if (u == 0) u = fa[tx], ss = caldis(ew[0], fa[tx]); jg = check(n, k, xl, fa[tx], u); if (jg == -1) printf("-1"); else { if (lx < ly) printf("%d %d %lld", lx, ly, jg + ss); else printf("%d %d %lld", ly, lx, jg + ss); } } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, a[N], b[N], s, t, deg[N]; vector<int> e1[N], f, g, Ap, Bp; int dfs1(int x, int fa) { f.push_back(x); if (x == t) return 1; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int check = dfs1(y, x); if (check) return 1; } } f.pop_back(); return 0; } int c[2]; bool vis[N]; void dfs2(int x, int fa, int k) { if (a[x] != b[x]) { g.push_back(x); vis[x] = 1; if (k - 1 == c[0] && fa != c[1]) printf("-1"), exit(0); if (k - 1 < c[0]) c[0] = k - 1, c[1] = fa; } int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) dfs2(y, x, k + 1); } return; } void dfs3(int x, int fa, int aim) { if (x != aim) Ap.push_back(a[x]), Bp.push_back(b[x]); int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa && vis[y]) dfs3(y, x, aim); } return; } int calc(vector<int> x, vector<int> y) { int res = 0, sizx = x.size(), sizy = y.size(); for (int i = 0; i < sizy; i++) if (y[i] == x[0]) res = i; if (res == 0) return -1; for (int i = 0; i < sizx; i++) if (x[i] != y[(i + res) % sizx]) return -1; return res; } int dfs4(int x, int fa, int dis, int aim) { if (x == aim) return dis; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int res = dfs4(y, x, dis + 1, aim); if (res != -1) return res; } } return -1; } long long solve(int x, int y) { int op1 = calc(Ap, Bp); long long res = dfs4(s, 0, 0, x) + 1ll * (op1 - 1) * (Ap.size() + 1) + 1 + dfs4(y, 0, 0, t); return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1; i <= n; i++) { if (a[i] == 0) s = i; if (b[i] == 0) t = i; } for (int i = 1; i <= n - 1; i++) { int x, y; scanf("%d%d", &x, &y); e1[x].push_back(y); e1[y].push_back(x); } dfs1(s, 0); int siz = f.size(); for (int i = 1; i < siz; i++) swap(a[f[i]], a[f[i - 1]]); bool check = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) check = 0; if (check) { printf("0 %d", siz - 1); return 0; } c[0] = n + 1, c[1] = 0; dfs2(t, 0, 0); int p1 = c[1]; vis[p1] = 1; g.push_back(p1); siz = g.size(); for (int i = 0; i < siz; i++) { int siz1 = e1[g[i]].size(); for (int j = 0; j < siz1; j++) { int y = e1[g[i]][j]; if (vis[y]) deg[g[i]]++; } } vector<int> h; for (int i = 0; i < siz; i++) if (deg[g[i]] == 1) h.push_back(g[i]); else if (deg[g[i]] != 2) return printf("-1"), 0; if (h.size() != 2) return printf("-1"), 0; if (h[0] > h[1]) swap(h[0], h[1]); dfs3(h[0], 0, p1); if (calc(Ap, Bp) == -1) return printf("-1"), 0; long long ans1 = solve(h[0], h[1]); int sizA = Ap.size(), sizB = Bp.size(); for (int i = 0; i < sizA; i++) if ((sizA - i - 1) > i) swap(Ap[i], Ap[sizA - i - 1]); for (int i = 0; i < sizB; i++) if ((sizB - i - 1) > i) swap(Bp[i], Bp[sizB - i - 1]); long long ans2 = solve(h[1], h[0]); printf("%d %d %lld", h[0], h[1], min(ans1, ans2)); return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, a[N], b[N], s, t, deg[N]; vector<int> e1[N], f, g, Ap, Bp; int dfs1(int x, int fa) { f.push_back(x); if (x == t) return 1; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int check = dfs1(y, x); if (check) return 1; } } f.pop_back(); return 0; } int c[2]; bool vis[N]; void dfs2(int x, int fa, int k) { if (a[x] != b[x]) { g.push_back(x); vis[x] = 1; if (k - 1 == c[0] && fa != c[1]) printf("-1"), exit(0); if (k - 1 < c[0]) c[0] = k - 1, c[1] = fa; } int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) dfs2(y, x, k + 1); } return; } void dfs3(int x, int fa, int aim) { if (x != aim) Ap.push_back(a[x]), Bp.push_back(b[x]); int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa && vis[y]) dfs3(y, x, aim); } return; } int calc(vector<int> x, vector<int> y) { int res = 0, sizx = x.size(), sizy = y.size(); for (int i = 0; i < sizy; i++) if (y[i] == x[0]) res = i; if (res == 0) return -1; for (int i = 0; i < sizx; i++) if (x[i] != y[(i + res) % sizx]) return -1; return res; } int dfs4(int x, int fa, int dis, int aim) { if (x == aim) return dis; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int res = dfs4(y, x, dis + 1, aim); if (res != -1) return res; } } return -1; } long long solve(int x, int y) { int op1 = calc(Ap, Bp); long long res = dfs4(s, 0, 0, x) + 1ll * (op1 - 1) * (Ap.size() + 1) + 1 + dfs4(y, 0, 0, t); return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1; i <= n; i++) { if (a[i] == 0) s = i; if (b[i] == 0) t = i; } for (int i = 1; i <= n - 1; i++) { int x, y; scanf("%d%d", &x, &y); e1[x].push_back(y); e1[y].push_back(x); } dfs1(s, 0); int siz = f.size(); for (int i = 1; i < siz; i++) swap(a[f[i]], a[f[i - 1]]); bool check = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) check = 0; if (check) { printf("0 %d", siz - 1); return 0; } c[0] = n + 1, c[1] = 0; dfs2(t, 0, 0); int p1 = c[1]; vis[p1] = 1; g.push_back(p1); siz = g.size(); for (int i = 0; i < siz; i++) { int siz1 = e1[g[i]].size(); for (int j = 0; j < siz1; j++) { int y = e1[g[i]][j]; if (vis[y]) deg[g[i]]++; } } vector<int> h; for (int i = 0; i < siz; i++) if (deg[g[i]] == 1) h.push_back(g[i]); else if (deg[g[i]] != 2) return printf("-1"), 0; if (h.size() != 2) return printf("-1"), 0; if (h[0] > h[1]) swap(h[0], h[1]); dfs3(h[0], 0, p1); if (calc(Ap, Bp) == -1) return printf("-1"), 0; long long ans1 = solve(h[0], h[1]); int sizA = Ap.size(), sizB = Bp.size(); for (int i = 0; i < sizA; i++) if ((sizA - i - 1) > i) swap(Ap[i], Ap[sizA - i - 1]); for (int i = 0; i < sizB; i++) if ((sizB - i - 1) > i) swap(Bp[i], Bp[sizB - i - 1]); long long ans2 = solve(h[1], h[0]); printf("%d %d %lld", h[0], h[1], min(ans1, ans2)); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 200005; int n, s, t, dep[N], fa[N], a[N], ta[N], b[N], p, u, v; vector<int> g[N], av, bv; bool mark[N]; void dfs(int u) { for (int v : g[u]) if (v != fa[u]) fa[v] = u, dep[v] = dep[u] + 1, dfs(v); } void get(int u) { if (u != p) av.push_back(ta[u]), bv.push_back(b[u]); mark[u] = true; bool flag = false; for (int v : g[u]) if (!mark[v] && (v == p || ta[v] != b[v])) { flag = true; get(v); break; } if (!flag) v = u; } int dis(int u, int v) { int d = 0; while (u != v) ++d, dep[u] > dep[v] ? u = fa[u] : v = fa[v]; return d; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i), ta[i] = a[i], !a[i] ? s = i : 0; for (int i = 1; i <= n; ++i) scanf("%d", b + i), !b[i] ? t = i : 0; for (int i = 1, x, y; i < n; ++i) { scanf("%d%d", &x, &y); g[x].push_back(y), g[y].push_back(x); } dfs(t); int cnt = 0; for (int u = s; u != t; u = fa[u]) ++cnt, swap(ta[u], ta[fa[u]]); p = -1; for (int i = 1; i <= n; ++i) if (ta[i] != b[i]) { if (p == -1 || dep[i] < dep[p]) p = i; if (dep[i] >= dep[u]) u = i; } if (p == -1) return printf("0 %d\n", cnt), 0; p = fa[p]; get(u); for (int i = 1; i <= n; ++i) if (mark[i] != (ta[i] != b[i] || i == p)) return puts("-1"), 0; int c = -1; for (int i = 0; i < bv.size(); ++i) if (bv[i] == av[0]) c = i; if (c == -1) return puts("-1"), 0; for (int i = 0; i < av.size(); ++i) if (av[i] != bv[(i + c) % av.size()]) return puts("-1"), 0; printf("%d %d %lld\n", min(u, v), max(u, v), min(dis(s, u) + 1 + (long long)(dis(u, v) + 1) * (c - 1) + dis(v, t), dis(s, v) + 1 + (dis(u, v) + 1) * ((long long)av.size() - c - 1) + dis(u, t))); }
### Prompt In CPP, your task is to solve the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200005; int n, s, t, dep[N], fa[N], a[N], ta[N], b[N], p, u, v; vector<int> g[N], av, bv; bool mark[N]; void dfs(int u) { for (int v : g[u]) if (v != fa[u]) fa[v] = u, dep[v] = dep[u] + 1, dfs(v); } void get(int u) { if (u != p) av.push_back(ta[u]), bv.push_back(b[u]); mark[u] = true; bool flag = false; for (int v : g[u]) if (!mark[v] && (v == p || ta[v] != b[v])) { flag = true; get(v); break; } if (!flag) v = u; } int dis(int u, int v) { int d = 0; while (u != v) ++d, dep[u] > dep[v] ? u = fa[u] : v = fa[v]; return d; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i), ta[i] = a[i], !a[i] ? s = i : 0; for (int i = 1; i <= n; ++i) scanf("%d", b + i), !b[i] ? t = i : 0; for (int i = 1, x, y; i < n; ++i) { scanf("%d%d", &x, &y); g[x].push_back(y), g[y].push_back(x); } dfs(t); int cnt = 0; for (int u = s; u != t; u = fa[u]) ++cnt, swap(ta[u], ta[fa[u]]); p = -1; for (int i = 1; i <= n; ++i) if (ta[i] != b[i]) { if (p == -1 || dep[i] < dep[p]) p = i; if (dep[i] >= dep[u]) u = i; } if (p == -1) return printf("0 %d\n", cnt), 0; p = fa[p]; get(u); for (int i = 1; i <= n; ++i) if (mark[i] != (ta[i] != b[i] || i == p)) return puts("-1"), 0; int c = -1; for (int i = 0; i < bv.size(); ++i) if (bv[i] == av[0]) c = i; if (c == -1) return puts("-1"), 0; for (int i = 0; i < av.size(); ++i) if (av[i] != bv[(i + c) % av.size()]) return puts("-1"), 0; printf("%d %d %lld\n", min(u, v), max(u, v), min(dis(s, u) + 1 + (long long)(dis(u, v) + 1) * (c - 1) + dis(v, t), dis(s, v) + 1 + (dis(u, v) + 1) * ((long long)av.size() - c - 1) + dis(u, t))); } ```
#include <bits/stdc++.h> using namespace std; const int INF = (int)1e9 + 100; const long long lINF = 1e18; const double EPS = 1e-12; int myrand() { return rand(); } long long rdtsc() { long long ans; asm("rdtsc" : "=A"(ans)); return ans; } int rnd(int x) { return myrand() % x; } const int maxn = (int)2e5 + 100; int n; int a[maxn], b[maxn], c[maxn]; int used[maxn], maxu, depth[maxn], par[maxn]; vector<int> tree[maxn]; bool read() { if (scanf("%d", &n) < 1) { return false; } for (int i = 0; i < n; i++) { scanf("%d", a + i); } for (int i = 0; i < n; i++) { scanf("%d", b + i); } for (int i = 0; i < n; i++) { tree[i].clear(); } for (int i = 0; i < n - 1; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; tree[u].push_back(v); tree[v].push_back(u); } return true; } void dfs(int v, int curpar = -1, int dep = 0) { depth[v] = dep; par[v] = curpar; for (int i = 0; i < ((int)((tree[v]).size())); i++) { int to = tree[v][i]; if (to == curpar) { continue; } dfs(to, v, dep + 1); } } int move0(int v, int* perm, int curpar = -1) { if (perm[v] == 0) { return 0; } for (int i = 0; i < ((int)((tree[v]).size())); i++) { int to = tree[v][i]; if (to == curpar || used[to] == maxu) { continue; } int res = move0(to, perm, v); if (res >= 0) { swap(perm[v], perm[to]); return res + 1; } } return -1; } void solve() { int root = (int)(find(a, a + n, 0) - a); dfs(root); memcpy(c, b, n * sizeof(int)); maxu++; int restree = move0(root, c); assert(a[root] == 0 && c[root] == 0); vector<int> ends; int anc = -1; for (int i = 0; i < n; i++) { if (a[i] != c[i]) { if (anc == -1 || depth[anc] > depth[par[i]]) { anc = par[i]; } bool leaf = true; for (int j = 0; j < ((int)((tree[i]).size())); j++) { int to = tree[i][j]; if (to == par[i]) { continue; } if (a[to] != c[to]) { leaf = false; break; } } if (leaf) { ends.push_back(i); } } } if (((int)((ends).size())) > 2) { printf("-1\n"); return; } if (((int)((ends).size())) == 0) { printf("0 %d\n", restree); return; } assert(anc != -1); if (((int)((ends).size())) == 1) { ends.push_back(anc); } vector<int> cycle, cycle1, cycle2; maxu++; for (int it = 0; it < 2; it++) { for (int i = ends[it]; i != anc; i = par[i]) { if (i == -1 || used[i] == maxu) { printf("-1\n"); return; } if (!it) { cycle1.push_back(i); } else { cycle2.push_back(i); } used[i] = maxu; } } cycle.push_back(anc); used[anc] = maxu; for (int i = ((int)((cycle2).size())) - 1; i >= 0; i--) { cycle.push_back(cycle2[i]); } for (int i = 0; i < ((int)((cycle1).size())); i++) { cycle.push_back(cycle1[i]); } int m = ((int)((cycle).size())); int res = 0; for (int i = 0; i < m; i++) { res += max(0, move0(cycle[i], a)); res += max(0, move0(cycle[i], b)); } vector<int> incycle(n, -1), inb(n); for (int i = 0; i < n; i++) { inb[b[i]] = i; } for (int i = 0; i < m; i++) { incycle[cycle[i]] = i; } vector<int> nperm(m); for (int i = 0; i < m; i++) { int val = incycle[inb[a[cycle[i]]]]; if (val == -1) { printf("-1\n"); return; } nperm[i] = val; } vector<int> rev(m); for (int i = 0; i < m; i++) { rev[nperm[i]] = i; } assert(m > 1); long long rescycle = lINF; vector<int> curperm = rev; for (int it = 0; it < 2; it++) { vector<int> now(m); int curres = 0; for (int i = 0; i < m; i++) { now[i] = i; } for (int i = 0; curperm[i] != 0; i++) { curres++; swap(now[i], now[i + 1]); } int diff = -1; for (int j = 0; j < m; j++) { if (now[j] != 0) { int curdiff = ((now[j] - curperm[j]) % (m - 1) + (m - 1)) % (m - 1); if (diff != -1 && curdiff != diff) { printf("-1\n"); return; } diff = curdiff; } } rescycle = min(rescycle, curres + (long long)(min(diff, m - 1 - diff)) * m); for (int i = 0; i < m; i++) { int j = !i ? 0 : (m - i); curperm[i] = rev[j] ? (m - rev[j]) : 0; } } if (ends[0] > ends[1]) { swap(ends[0], ends[1]); } printf( "%d %d " "%lld" "\n", ends[0] + 1, ends[1] + 1, rescycle + res); } int main() { srand(rdtsc()); while (true) { if (!read()) { break; } solve(); break; fprintf(stderr, "Time: %.18f\n", (double)clock() / CLOCKS_PER_SEC); fflush(stderr); } return 0; }
### Prompt Your task is to create a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int INF = (int)1e9 + 100; const long long lINF = 1e18; const double EPS = 1e-12; int myrand() { return rand(); } long long rdtsc() { long long ans; asm("rdtsc" : "=A"(ans)); return ans; } int rnd(int x) { return myrand() % x; } const int maxn = (int)2e5 + 100; int n; int a[maxn], b[maxn], c[maxn]; int used[maxn], maxu, depth[maxn], par[maxn]; vector<int> tree[maxn]; bool read() { if (scanf("%d", &n) < 1) { return false; } for (int i = 0; i < n; i++) { scanf("%d", a + i); } for (int i = 0; i < n; i++) { scanf("%d", b + i); } for (int i = 0; i < n; i++) { tree[i].clear(); } for (int i = 0; i < n - 1; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; tree[u].push_back(v); tree[v].push_back(u); } return true; } void dfs(int v, int curpar = -1, int dep = 0) { depth[v] = dep; par[v] = curpar; for (int i = 0; i < ((int)((tree[v]).size())); i++) { int to = tree[v][i]; if (to == curpar) { continue; } dfs(to, v, dep + 1); } } int move0(int v, int* perm, int curpar = -1) { if (perm[v] == 0) { return 0; } for (int i = 0; i < ((int)((tree[v]).size())); i++) { int to = tree[v][i]; if (to == curpar || used[to] == maxu) { continue; } int res = move0(to, perm, v); if (res >= 0) { swap(perm[v], perm[to]); return res + 1; } } return -1; } void solve() { int root = (int)(find(a, a + n, 0) - a); dfs(root); memcpy(c, b, n * sizeof(int)); maxu++; int restree = move0(root, c); assert(a[root] == 0 && c[root] == 0); vector<int> ends; int anc = -1; for (int i = 0; i < n; i++) { if (a[i] != c[i]) { if (anc == -1 || depth[anc] > depth[par[i]]) { anc = par[i]; } bool leaf = true; for (int j = 0; j < ((int)((tree[i]).size())); j++) { int to = tree[i][j]; if (to == par[i]) { continue; } if (a[to] != c[to]) { leaf = false; break; } } if (leaf) { ends.push_back(i); } } } if (((int)((ends).size())) > 2) { printf("-1\n"); return; } if (((int)((ends).size())) == 0) { printf("0 %d\n", restree); return; } assert(anc != -1); if (((int)((ends).size())) == 1) { ends.push_back(anc); } vector<int> cycle, cycle1, cycle2; maxu++; for (int it = 0; it < 2; it++) { for (int i = ends[it]; i != anc; i = par[i]) { if (i == -1 || used[i] == maxu) { printf("-1\n"); return; } if (!it) { cycle1.push_back(i); } else { cycle2.push_back(i); } used[i] = maxu; } } cycle.push_back(anc); used[anc] = maxu; for (int i = ((int)((cycle2).size())) - 1; i >= 0; i--) { cycle.push_back(cycle2[i]); } for (int i = 0; i < ((int)((cycle1).size())); i++) { cycle.push_back(cycle1[i]); } int m = ((int)((cycle).size())); int res = 0; for (int i = 0; i < m; i++) { res += max(0, move0(cycle[i], a)); res += max(0, move0(cycle[i], b)); } vector<int> incycle(n, -1), inb(n); for (int i = 0; i < n; i++) { inb[b[i]] = i; } for (int i = 0; i < m; i++) { incycle[cycle[i]] = i; } vector<int> nperm(m); for (int i = 0; i < m; i++) { int val = incycle[inb[a[cycle[i]]]]; if (val == -1) { printf("-1\n"); return; } nperm[i] = val; } vector<int> rev(m); for (int i = 0; i < m; i++) { rev[nperm[i]] = i; } assert(m > 1); long long rescycle = lINF; vector<int> curperm = rev; for (int it = 0; it < 2; it++) { vector<int> now(m); int curres = 0; for (int i = 0; i < m; i++) { now[i] = i; } for (int i = 0; curperm[i] != 0; i++) { curres++; swap(now[i], now[i + 1]); } int diff = -1; for (int j = 0; j < m; j++) { if (now[j] != 0) { int curdiff = ((now[j] - curperm[j]) % (m - 1) + (m - 1)) % (m - 1); if (diff != -1 && curdiff != diff) { printf("-1\n"); return; } diff = curdiff; } } rescycle = min(rescycle, curres + (long long)(min(diff, m - 1 - diff)) * m); for (int i = 0; i < m; i++) { int j = !i ? 0 : (m - i); curperm[i] = rev[j] ? (m - rev[j]) : 0; } } if (ends[0] > ends[1]) { swap(ends[0], ends[1]); } printf( "%d %d " "%lld" "\n", ends[0] + 1, ends[1] + 1, rescycle + res); } int main() { srand(rdtsc()); while (true) { if (!read()) { break; } solve(); break; fprintf(stderr, "Time: %.18f\n", (double)clock() / CLOCKS_PER_SEC); fflush(stderr); } return 0; } ```
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); } return x * f; } int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; }
### Prompt Develop a solution in CPP to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); } return x * f; } int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, ca[N], cb[N], u[N], v[N], i, j, z, S, T, deg[N], id[N], X; long long ans; vector<int> e[N], ep; multiset<int> SS; bool b1[N]; int dad[N], dep[N]; void dfs(int x, int fa) { dep[x] = dep[fa] + 1; dad[x] = fa; for (int y : e[x]) if (y != fa) dfs(y, x); } inline vector<int> getP(int x, int y) { dfs(y, 0); vector<int> ans; for (; ans.push_back(x), x != y; x = dad[x]) ; return ans; } inline void shift(vector<int>& a, int d) { vector<int> b = vector<int>(a.begin(), a.begin() + d); a = vector<int>(a.begin() + d, a.end()); a.insert(a.end(), b.begin(), b.end()); } int dfs2(int x, int fa) { if (x == X) return !id[x]; if (b1[x]) { puts("-1"); exit(0); } for (int y : e[x]) if (y != fa) { int t = dfs2(y, x); if (t != -1) return t + !id[x]; } return -1; } int main() { scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d", ca + i), ca[i] ? 0 : S = i; for (i = 1; i <= n; ++i) scanf("%d", cb + i), cb[i] ? 0 : T = i; for (i = 1; i < n; ++i) scanf("%d%d", u + i, v + i), e[u[i]].push_back(v[i]), e[v[i]].push_back(u[i]); auto zz = getP(S, T); for (i = 0; i + 1 < zz.size(); ++i) swap(ca[zz[i]], ca[zz[i + 1]]), ++ans; for (i = 0; i < zz.size(); ++i) id[zz[i]] = i + 1; for (i = 1; i <= n; ++i) b1[i] = ca[i] != cb[i]; for (i = 1; i < n; ++i) if (b1[u[i]] && b1[v[i]]) ++deg[u[i]], ++deg[v[i]]; for (i = 1; i <= n; ++i) if (b1[i] && deg[i] < 2) for (int x = 2 - deg[i]; x--;) SS.insert(i); if (SS.empty()) { printf("0 %lld\n", ans); return 0; } if (SS.size() == 2) { int mn = N, mnid = 0; dfs(T, 0); for (i = 1; i <= n; ++i) if (b1[i] && dep[i] < mn) mn = dep[i], mnid = i; if (deg[mnid] > 1) { puts("-1"); return 0; } X = dad[mnid]; ep = {X, *SS.begin() ^ *SS.rbegin() ^ mnid}; } else if (SS.size() == 4) { for (i = 1; i <= n; ++i) if (!b1[i]) { int ct = 0; for (int j : e[i]) ct += b1[j] && deg[j] < 2; if (ct == 2) break; } if (i > n) { puts("-1"); return 0; } X = i; for (int j : e[i]) if (b1[j] && deg[j] < 2) SS.erase(SS.find(j)); ep = {*SS.begin(), *SS.rbegin()}; } else { puts("-1"); return 0; } auto p0 = getP(ep[0], ep[1]), pp0 = p0; p0.erase(find(p0.begin(), p0.end(), X)); auto p1 = p0, p2 = p0; for (int& x : p1) x = ca[x]; for (int& y : p2) y = cb[y]; for (i = 0; i < p1.size() && p1[i] != p2[0]; ++i) ; if (i == p1.size()) { puts("-1"); return 0; } shift(p1, i); if (p1 != p2) { puts("-1"); return 0; } for (int x : p0) z += id[x] > 0; if (z < 1) { ans += dfs2(T, 0) * 2; ans += 1ll * (p0.size() + 1) * min(int(p0.size() - i), i); } else { p0 = pp0; p0.push_back(p0[0]); long long v1 = 1ll * (p0.size() - 1) * i, v2 = 1ll * (p0.size() - 1) * (p1.size() - i); if (v1) for (j = 0; j + 1 < p0.size(); ++j) v1 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] - 1 == id[p0[j + 1]]) * 2; if (v2) for (j = 0; j + 1 < p0.size(); ++j) v2 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] + 1 == id[p0[j + 1]]) * 2; ans += min(v1, v2); } sort(ep.begin(), ep.end()); printf("%d %d %lld\n", ep[0], ep[1], ans); return 0; }
### Prompt Develop a solution in cpp to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, ca[N], cb[N], u[N], v[N], i, j, z, S, T, deg[N], id[N], X; long long ans; vector<int> e[N], ep; multiset<int> SS; bool b1[N]; int dad[N], dep[N]; void dfs(int x, int fa) { dep[x] = dep[fa] + 1; dad[x] = fa; for (int y : e[x]) if (y != fa) dfs(y, x); } inline vector<int> getP(int x, int y) { dfs(y, 0); vector<int> ans; for (; ans.push_back(x), x != y; x = dad[x]) ; return ans; } inline void shift(vector<int>& a, int d) { vector<int> b = vector<int>(a.begin(), a.begin() + d); a = vector<int>(a.begin() + d, a.end()); a.insert(a.end(), b.begin(), b.end()); } int dfs2(int x, int fa) { if (x == X) return !id[x]; if (b1[x]) { puts("-1"); exit(0); } for (int y : e[x]) if (y != fa) { int t = dfs2(y, x); if (t != -1) return t + !id[x]; } return -1; } int main() { scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d", ca + i), ca[i] ? 0 : S = i; for (i = 1; i <= n; ++i) scanf("%d", cb + i), cb[i] ? 0 : T = i; for (i = 1; i < n; ++i) scanf("%d%d", u + i, v + i), e[u[i]].push_back(v[i]), e[v[i]].push_back(u[i]); auto zz = getP(S, T); for (i = 0; i + 1 < zz.size(); ++i) swap(ca[zz[i]], ca[zz[i + 1]]), ++ans; for (i = 0; i < zz.size(); ++i) id[zz[i]] = i + 1; for (i = 1; i <= n; ++i) b1[i] = ca[i] != cb[i]; for (i = 1; i < n; ++i) if (b1[u[i]] && b1[v[i]]) ++deg[u[i]], ++deg[v[i]]; for (i = 1; i <= n; ++i) if (b1[i] && deg[i] < 2) for (int x = 2 - deg[i]; x--;) SS.insert(i); if (SS.empty()) { printf("0 %lld\n", ans); return 0; } if (SS.size() == 2) { int mn = N, mnid = 0; dfs(T, 0); for (i = 1; i <= n; ++i) if (b1[i] && dep[i] < mn) mn = dep[i], mnid = i; if (deg[mnid] > 1) { puts("-1"); return 0; } X = dad[mnid]; ep = {X, *SS.begin() ^ *SS.rbegin() ^ mnid}; } else if (SS.size() == 4) { for (i = 1; i <= n; ++i) if (!b1[i]) { int ct = 0; for (int j : e[i]) ct += b1[j] && deg[j] < 2; if (ct == 2) break; } if (i > n) { puts("-1"); return 0; } X = i; for (int j : e[i]) if (b1[j] && deg[j] < 2) SS.erase(SS.find(j)); ep = {*SS.begin(), *SS.rbegin()}; } else { puts("-1"); return 0; } auto p0 = getP(ep[0], ep[1]), pp0 = p0; p0.erase(find(p0.begin(), p0.end(), X)); auto p1 = p0, p2 = p0; for (int& x : p1) x = ca[x]; for (int& y : p2) y = cb[y]; for (i = 0; i < p1.size() && p1[i] != p2[0]; ++i) ; if (i == p1.size()) { puts("-1"); return 0; } shift(p1, i); if (p1 != p2) { puts("-1"); return 0; } for (int x : p0) z += id[x] > 0; if (z < 1) { ans += dfs2(T, 0) * 2; ans += 1ll * (p0.size() + 1) * min(int(p0.size() - i), i); } else { p0 = pp0; p0.push_back(p0[0]); long long v1 = 1ll * (p0.size() - 1) * i, v2 = 1ll * (p0.size() - 1) * (p1.size() - i); if (v1) for (j = 0; j + 1 < p0.size(); ++j) v1 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] - 1 == id[p0[j + 1]]) * 2; if (v2) for (j = 0; j + 1 < p0.size(); ++j) v2 -= (id[p0[j]] && id[p0[j + 1]] && id[p0[j]] + 1 == id[p0[j + 1]]) * 2; ans += min(v1, v2); } sort(ep.begin(), ep.end()); printf("%d %d %lld\n", ep[0], ep[1], ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 4e5 + 5; vector<int> adj[maxn]; int a[maxn], b[maxn], n, par[maxn], a0, b0; long long ans; int dep[maxn], id[maxn], idx; vector<pair<int, int> > chain; bool vis[maxn]; void dfs(int u) { id[++idx] = u; for (auto v : adj[u]) if (v != par[u]) { par[v] = u; dep[v] = dep[u] + 1; dfs(v); } } int lca(int u, int v) { if (dep[u] < dep[v]) swap(u, v); while (dep[u] > dep[v]) u = par[u]; while (u != v) u = par[u], v = par[v]; return u; } int dist(int u, int v) { return dep[u] + dep[v] - 2 * dep[lca(u, v)]; } int stk[maxn]; void move(int *a, int u, int v) { int t = lca(u, v), top = 0; for (int i = u; i != t; i = par[i]) swap(a[par[i]], a[i]); for (int i = v; i != t; i = par[i]) stk[++top] = i; while (top) swap(a[par[stk[top]]], a[stk[top]]), --top; } bool check() { for (int i = 1; i <= (n); i++) if (a[i] != b[i]) return false; return true; } int cir[maxn], tot; int main() { scanf("%d", &n); for (int i = 1; i <= (n); i++) scanf("%d", &a[i]); for (int i = 1; i <= (n); i++) scanf("%d", &b[i]); for (int u, v, i = 1; i < n; i++) scanf("%d %d", &u, &v), adj[u].push_back(v), adj[v].push_back(u); for (int i = 1; i <= (n); i++) a[i] == 0 ? a0 = i : 0; for (int i = 1; i <= (n); i++) b[i] == 0 ? b0 = i : 0; dfs(b0); move(a, a0, b0); if (check()) { printf("0 %d", dist(a0, b0)); return 0; } for (int i = 1; i <= (n); i++) if (a[i] == b[i]) vis[i] = true; for (int i = (n); i >= 1; i--) if (!vis[id[i]]) { int u = id[i], v = u; vis[u] = true; while (par[v] && !vis[par[v]]) v = par[v], vis[v] = true; chain.push_back(pair<int, int>(u, v)); } move(a, b0, a0); if (chain.size() > 2) { printf("-1"); return 0; } if (chain.size() == 2) { if (par[chain[0].second] != par[chain[1].second]) { printf("-1"); return 0; } int t = par[chain[0].second], ansu = chain[0].first, ansv = chain[1].first; for (int i = ansu; i != t; i = par[i]) cir[++tot] = i; int mid = tot; for (int i = ansv; i != t; i = par[i]) cir[++tot] = i; reverse(cir + mid + 1, cir + tot + 1); int brk = t, tmp = 0; if (dep[lca(a0, ansu)] > dep[brk]) { brk = lca(a0, ansu); tmp = dist(brk, t); move(a, a0, brk); move(b, b0, t); move(a, brk, t); } else if (dep[lca(a0, ansv)] > dep[brk]) { brk = lca(a0, ansv); tmp = tot + 1 - dist(brk, t); move(a, a0, brk); move(b, b0, t); move(a, brk, ansv); swap(a[ansu], a[ansv]); move(a, ansu, t); } else { move(a, a0, t); move(b, b0, t); } ans = dist(a0, brk) + dist(b0, t); int shift = 0; for (int i = 1; i <= (tot); i++) cir[i + tot] = cir[i]; for (int i = 1; i <= (tot); i++) if (a[cir[i]] == b[cir[1]]) shift = i - 1; for (int i = 1; i <= (tot); i++) if (a[cir[i + shift]] != b[cir[i]]) { printf("-1"); return 0; } ans += min((long long)(tot + 1) * (tot - shift) - tmp, (long long)(tot + 1) * shift + tmp); if (ansu > ansv) swap(ansu, ansv); printf("%d %d %I64d", ansu, ansv, ans); } if (chain.size() == 1) { int bot = chain[0].first, t = par[chain[0].second]; for (int i = bot; i != t; i = par[i]) cir[++tot] = i; int brk = lca(a0, bot); dep[brk] < dep[t] ? brk = t : 0; ans = dist(a0, brk) + dist(b0, t); move(a, a0, brk); move(b, b0, t); int tmp = dist(brk, t), shift = 0; move(a, brk, t); for (int i = 1; i <= (tot); i++) cir[i + tot] = cir[i]; for (int i = 1; i <= (tot); i++) if (a[cir[i]] == b[cir[1]]) shift = i - 1; for (int i = 1; i <= (tot); i++) if (a[cir[i + shift]] != b[cir[i]]) { printf("-1"); return 0; } ans += min((long long)(tot + 1) * (tot - shift) - tmp, (long long)(tot + 1) * shift + tmp); if (bot > t) swap(bot, t); printf("%d %d %I64d", bot, t, ans); } return 0; }
### Prompt Develop a solution in CPP to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 4e5 + 5; vector<int> adj[maxn]; int a[maxn], b[maxn], n, par[maxn], a0, b0; long long ans; int dep[maxn], id[maxn], idx; vector<pair<int, int> > chain; bool vis[maxn]; void dfs(int u) { id[++idx] = u; for (auto v : adj[u]) if (v != par[u]) { par[v] = u; dep[v] = dep[u] + 1; dfs(v); } } int lca(int u, int v) { if (dep[u] < dep[v]) swap(u, v); while (dep[u] > dep[v]) u = par[u]; while (u != v) u = par[u], v = par[v]; return u; } int dist(int u, int v) { return dep[u] + dep[v] - 2 * dep[lca(u, v)]; } int stk[maxn]; void move(int *a, int u, int v) { int t = lca(u, v), top = 0; for (int i = u; i != t; i = par[i]) swap(a[par[i]], a[i]); for (int i = v; i != t; i = par[i]) stk[++top] = i; while (top) swap(a[par[stk[top]]], a[stk[top]]), --top; } bool check() { for (int i = 1; i <= (n); i++) if (a[i] != b[i]) return false; return true; } int cir[maxn], tot; int main() { scanf("%d", &n); for (int i = 1; i <= (n); i++) scanf("%d", &a[i]); for (int i = 1; i <= (n); i++) scanf("%d", &b[i]); for (int u, v, i = 1; i < n; i++) scanf("%d %d", &u, &v), adj[u].push_back(v), adj[v].push_back(u); for (int i = 1; i <= (n); i++) a[i] == 0 ? a0 = i : 0; for (int i = 1; i <= (n); i++) b[i] == 0 ? b0 = i : 0; dfs(b0); move(a, a0, b0); if (check()) { printf("0 %d", dist(a0, b0)); return 0; } for (int i = 1; i <= (n); i++) if (a[i] == b[i]) vis[i] = true; for (int i = (n); i >= 1; i--) if (!vis[id[i]]) { int u = id[i], v = u; vis[u] = true; while (par[v] && !vis[par[v]]) v = par[v], vis[v] = true; chain.push_back(pair<int, int>(u, v)); } move(a, b0, a0); if (chain.size() > 2) { printf("-1"); return 0; } if (chain.size() == 2) { if (par[chain[0].second] != par[chain[1].second]) { printf("-1"); return 0; } int t = par[chain[0].second], ansu = chain[0].first, ansv = chain[1].first; for (int i = ansu; i != t; i = par[i]) cir[++tot] = i; int mid = tot; for (int i = ansv; i != t; i = par[i]) cir[++tot] = i; reverse(cir + mid + 1, cir + tot + 1); int brk = t, tmp = 0; if (dep[lca(a0, ansu)] > dep[brk]) { brk = lca(a0, ansu); tmp = dist(brk, t); move(a, a0, brk); move(b, b0, t); move(a, brk, t); } else if (dep[lca(a0, ansv)] > dep[brk]) { brk = lca(a0, ansv); tmp = tot + 1 - dist(brk, t); move(a, a0, brk); move(b, b0, t); move(a, brk, ansv); swap(a[ansu], a[ansv]); move(a, ansu, t); } else { move(a, a0, t); move(b, b0, t); } ans = dist(a0, brk) + dist(b0, t); int shift = 0; for (int i = 1; i <= (tot); i++) cir[i + tot] = cir[i]; for (int i = 1; i <= (tot); i++) if (a[cir[i]] == b[cir[1]]) shift = i - 1; for (int i = 1; i <= (tot); i++) if (a[cir[i + shift]] != b[cir[i]]) { printf("-1"); return 0; } ans += min((long long)(tot + 1) * (tot - shift) - tmp, (long long)(tot + 1) * shift + tmp); if (ansu > ansv) swap(ansu, ansv); printf("%d %d %I64d", ansu, ansv, ans); } if (chain.size() == 1) { int bot = chain[0].first, t = par[chain[0].second]; for (int i = bot; i != t; i = par[i]) cir[++tot] = i; int brk = lca(a0, bot); dep[brk] < dep[t] ? brk = t : 0; ans = dist(a0, brk) + dist(b0, t); move(a, a0, brk); move(b, b0, t); int tmp = dist(brk, t), shift = 0; move(a, brk, t); for (int i = 1; i <= (tot); i++) cir[i + tot] = cir[i]; for (int i = 1; i <= (tot); i++) if (a[cir[i]] == b[cir[1]]) shift = i - 1; for (int i = 1; i <= (tot); i++) if (a[cir[i + shift]] != b[cir[i]]) { printf("-1"); return 0; } ans += min((long long)(tot + 1) * (tot - shift) - tmp, (long long)(tot + 1) * shift + tmp); if (bot > t) swap(bot, t); printf("%d %d %I64d", bot, t, ans); } return 0; } ```
#include <bits/stdc++.h> const int Maxn = 200000; void output_no_ans() { puts("-1"); exit(0); } int n; int head[Maxn + 5], arrive[Maxn << 1 | 5], nxt[Maxn << 1 | 5], tot; void add_edge(int from, int to) { arrive[++tot] = to; nxt[tot] = head[from]; head[from] = tot; } int a[Maxn + 5], b[Maxn + 5]; int fa[Maxn + 5]; int dep[Maxn + 5], pos[Maxn + 5]; void init_dfs_1(int u) { dep[u] = dep[fa[u]] + 1; for (int i = head[u]; i; i = nxt[i]) { int v = arrive[i]; if (v == fa[u]) { continue; } fa[v] = u; init_dfs_1(v); } } bool vis[Maxn + 5]; void work_1() { int u = pos[1]; int ans = dep[u]; while (u != 1) { vis[u] = 1; std::swap(b[u], b[fa[u]]); u = fa[u]; } vis[1] = 1; for (int i = 1; i <= n; i++) { if (b[i] != i) { return; } } printf("0 %d\n", ans); exit(0); } std::vector<int> lis[2]; int num; void get_path(int u) { if (num == 2 || (num == 1 && fa[u] != fa[lis[0][0]])) { output_no_ans(); } while (u) { lis[num].push_back(u); int v = 0; for (int i = head[u]; i; i = nxt[i]) { if (arrive[i] != fa[u] && b[arrive[i]] != arrive[i]) { if (v == 0) { v = arrive[i]; } else { output_no_ans(); } } } u = v; } num++; } void init_dfs_2(int u) { for (int i = head[u]; i; i = nxt[i]) { int v = arrive[i]; if (v == fa[u]) { continue; } if (b[v] == v) { init_dfs_2(v); } else { get_path(v); } } } int tmp[Maxn + 5], ori[Maxn + 5]; void work_2() { int u, v, x; if (num == 1) { x = u = fa[lis[0][0]]; v = lis[0].back(); } else { x = fa[lis[0][0]]; u = lis[0].back(); v = lis[1].back(); for (int i = 1; i <= (int)lis[1].size(); i++) { lis[0].push_back(lis[1][(int)lis[1].size() - i]); } } memset(tmp, -1, sizeof tmp); int k = 0, num = lis[0].size(); for (int i = 0; i < num; i++) { tmp[lis[0][i]] = i; } for (int i = 1; i <= n; i++) { if (tmp[i] == -1 && b[i] != i) { output_no_ans(); } } for (int i = 0; i < num; i++) { int val = (tmp[b[lis[0][i]]] + num - i) % num; if (i == 0) { k = val; } else if (k != val) { output_no_ans(); } } int dis = dep[u] + dep[v] - (dep[x] << 1) + 1; long long ans; if (!vis[x]) { k = std::min(k, num - k); ans = 1ll * k * dis; while (!vis[x]) { ans += 2; x = fa[x]; } ans += dep[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { cnt += vis[lis[0][i]]; } if (vis[lis[0][0]]) { ans = std::min(dis * k, dis * (num - k) - (cnt << 1)) + dep[pos[1]]; } else { ans = std::min(dis * k - (cnt << 1), dis * (num - k)) + dep[pos[1]]; } } u = ori[u], v = ori[v]; if (u > v) { std::swap(u, v); } printf("%d %d %lld\n", u, v, ans); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); u = a[u], v = a[v]; add_edge(u, v), add_edge(v, u); } dep[0] = -1; init_dfs_1(1); work_1(); init_dfs_2(1); work_2(); return 0; }
### Prompt Please formulate a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> const int Maxn = 200000; void output_no_ans() { puts("-1"); exit(0); } int n; int head[Maxn + 5], arrive[Maxn << 1 | 5], nxt[Maxn << 1 | 5], tot; void add_edge(int from, int to) { arrive[++tot] = to; nxt[tot] = head[from]; head[from] = tot; } int a[Maxn + 5], b[Maxn + 5]; int fa[Maxn + 5]; int dep[Maxn + 5], pos[Maxn + 5]; void init_dfs_1(int u) { dep[u] = dep[fa[u]] + 1; for (int i = head[u]; i; i = nxt[i]) { int v = arrive[i]; if (v == fa[u]) { continue; } fa[v] = u; init_dfs_1(v); } } bool vis[Maxn + 5]; void work_1() { int u = pos[1]; int ans = dep[u]; while (u != 1) { vis[u] = 1; std::swap(b[u], b[fa[u]]); u = fa[u]; } vis[1] = 1; for (int i = 1; i <= n; i++) { if (b[i] != i) { return; } } printf("0 %d\n", ans); exit(0); } std::vector<int> lis[2]; int num; void get_path(int u) { if (num == 2 || (num == 1 && fa[u] != fa[lis[0][0]])) { output_no_ans(); } while (u) { lis[num].push_back(u); int v = 0; for (int i = head[u]; i; i = nxt[i]) { if (arrive[i] != fa[u] && b[arrive[i]] != arrive[i]) { if (v == 0) { v = arrive[i]; } else { output_no_ans(); } } } u = v; } num++; } void init_dfs_2(int u) { for (int i = head[u]; i; i = nxt[i]) { int v = arrive[i]; if (v == fa[u]) { continue; } if (b[v] == v) { init_dfs_2(v); } else { get_path(v); } } } int tmp[Maxn + 5], ori[Maxn + 5]; void work_2() { int u, v, x; if (num == 1) { x = u = fa[lis[0][0]]; v = lis[0].back(); } else { x = fa[lis[0][0]]; u = lis[0].back(); v = lis[1].back(); for (int i = 1; i <= (int)lis[1].size(); i++) { lis[0].push_back(lis[1][(int)lis[1].size() - i]); } } memset(tmp, -1, sizeof tmp); int k = 0, num = lis[0].size(); for (int i = 0; i < num; i++) { tmp[lis[0][i]] = i; } for (int i = 1; i <= n; i++) { if (tmp[i] == -1 && b[i] != i) { output_no_ans(); } } for (int i = 0; i < num; i++) { int val = (tmp[b[lis[0][i]]] + num - i) % num; if (i == 0) { k = val; } else if (k != val) { output_no_ans(); } } int dis = dep[u] + dep[v] - (dep[x] << 1) + 1; long long ans; if (!vis[x]) { k = std::min(k, num - k); ans = 1ll * k * dis; while (!vis[x]) { ans += 2; x = fa[x]; } ans += dep[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { cnt += vis[lis[0][i]]; } if (vis[lis[0][0]]) { ans = std::min(dis * k, dis * (num - k) - (cnt << 1)) + dep[pos[1]]; } else { ans = std::min(dis * k - (cnt << 1), dis * (num - k)) + dep[pos[1]]; } } u = ori[u], v = ori[v]; if (u > v) { std::swap(u, v); } printf("%d %d %lld\n", u, v, ans); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); u = a[u], v = a[v]; add_edge(u, v), add_edge(v, u); } dep[0] = -1; init_dfs_1(1); work_1(); init_dfs_2(1); work_2(); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, a[N], b[N], s, t, v[N], d[N], p; vector<int> to[N], g, h, A, B; pair<int, int> key(N, 0); int dfs1(int x, int pre) { g.push_back(x); if (x == t) return 1; for (auto y : to[x]) if (y != pre && dfs1(y, x)) return 1; g.pop_back(); return 0; } void dfs2(int x, int pre, int d) { if (a[x] ^ b[x]) { h.push_back(x); v[x] = 1; if (d - 1 == key.first && pre != key.second) cout << -1 << endl, exit(0); if (d - 1 < key.first) key = make_pair(d - 1, pre); } for (auto y : to[x]) if (y != pre) dfs2(y, x, d + 1); } void dfs3(int x, int pre) { if (x != p) A.push_back(a[x]), B.push_back(b[x]); for (auto y : to[x]) if (y != pre && v[y]) dfs3(y, x); } int calc(vector<int> &A, vector<int> &B) { int pos = 0, sz = A.size(); for (int i = 0; i < B.size(); ++i) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (int i = 0; i < A.size(); ++i) if (A[i] != B[(i + pos) % sz]) return 0; return pos; } int dfs4(int x, int pre, int d, int t) { if (x == t) return d; for (auto y : to[x]) if (y != pre) { int o = dfs4(y, x, d + 1, t); if (o) return o; } return 0; } int len(int x, int y) { return dfs4(x, 0, 0, y); } long long get(int x, int y) { int c = calc(A, B); return len(s, x) + 1ll * (c - 1) * (A.size() + 1) + 1 + len(y, t); } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (!a[i]) s = i; } for (int i = 1; i <= n; ++i) { cin >> b[i]; if (!b[i]) t = i; } for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; to[x].push_back(y), to[y].push_back(x); } dfs1(s, 0); for (int i = 1; i < g.size(); ++i) swap(a[g[i - 1]], a[g[i]]); bool ok = 1; for (int i = 1; i <= n; ++i) ok &= a[i] == b[i]; if (ok) return cout << 0 << ' ' << g.size() - 1 << endl, 0; dfs2(t, 0, 0), h.push_back(p = key.second); v[p] = 1; for (auto x : h) for (auto y : to[x]) if (v[y]) ++d[x]; vector<int> u; for (auto x : h) if (d[x] == 1) u.push_back(x); else if (d[x] != 2) cout << -1 << endl, exit(0); if (u.size() != 2) cout << -1 << endl, exit(0); if (u[0] > u[1]) swap(u[0], u[1]); dfs3(u[0], 0); if (!calc(A, B)) cout << -1 << endl, exit(0); cout << u[0] << ' ' << u[1] << ' '; long long ans = get(u[0], u[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); cout << min(ans, get(u[1], u[0])) << endl; return 0; }
### Prompt Construct a CPP code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, a[N], b[N], s, t, v[N], d[N], p; vector<int> to[N], g, h, A, B; pair<int, int> key(N, 0); int dfs1(int x, int pre) { g.push_back(x); if (x == t) return 1; for (auto y : to[x]) if (y != pre && dfs1(y, x)) return 1; g.pop_back(); return 0; } void dfs2(int x, int pre, int d) { if (a[x] ^ b[x]) { h.push_back(x); v[x] = 1; if (d - 1 == key.first && pre != key.second) cout << -1 << endl, exit(0); if (d - 1 < key.first) key = make_pair(d - 1, pre); } for (auto y : to[x]) if (y != pre) dfs2(y, x, d + 1); } void dfs3(int x, int pre) { if (x != p) A.push_back(a[x]), B.push_back(b[x]); for (auto y : to[x]) if (y != pre && v[y]) dfs3(y, x); } int calc(vector<int> &A, vector<int> &B) { int pos = 0, sz = A.size(); for (int i = 0; i < B.size(); ++i) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (int i = 0; i < A.size(); ++i) if (A[i] != B[(i + pos) % sz]) return 0; return pos; } int dfs4(int x, int pre, int d, int t) { if (x == t) return d; for (auto y : to[x]) if (y != pre) { int o = dfs4(y, x, d + 1, t); if (o) return o; } return 0; } int len(int x, int y) { return dfs4(x, 0, 0, y); } long long get(int x, int y) { int c = calc(A, B); return len(s, x) + 1ll * (c - 1) * (A.size() + 1) + 1 + len(y, t); } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (!a[i]) s = i; } for (int i = 1; i <= n; ++i) { cin >> b[i]; if (!b[i]) t = i; } for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; to[x].push_back(y), to[y].push_back(x); } dfs1(s, 0); for (int i = 1; i < g.size(); ++i) swap(a[g[i - 1]], a[g[i]]); bool ok = 1; for (int i = 1; i <= n; ++i) ok &= a[i] == b[i]; if (ok) return cout << 0 << ' ' << g.size() - 1 << endl, 0; dfs2(t, 0, 0), h.push_back(p = key.second); v[p] = 1; for (auto x : h) for (auto y : to[x]) if (v[y]) ++d[x]; vector<int> u; for (auto x : h) if (d[x] == 1) u.push_back(x); else if (d[x] != 2) cout << -1 << endl, exit(0); if (u.size() != 2) cout << -1 << endl, exit(0); if (u[0] > u[1]) swap(u[0], u[1]); dfs3(u[0], 0); if (!calc(A, B)) cout << -1 << endl, exit(0); cout << u[0] << ' ' << u[1] << ' '; long long ans = get(u[0], u[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); cout << min(ans, get(u[1], u[0])) << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; inline char gc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline int read() { char c = getchar(); int tot = 1; while ((c < '0' || c > '9') && c != '-') c = getchar(); if (c == '-') { tot = -1; c = getchar(); } int sum = 0; while (c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); } return sum * tot; } inline void wr(int x) { if (x < 0) { putchar('-'); wr(-x); return; } if (x >= 10) wr(x / 10); putchar(x % 10 + '0'); } inline void wrn(int x) { wr(x); putchar('\n'); } inline void wri(int x) { wr(x); putchar(' '); } inline void wrn(int x, int y) { wri(x); wrn(y); } inline void wrn(int a, int b, int c) { wri(a); wrn(b, c); } int n, m, fa[500055], vis[500055], a[500055], b[500055], s1, s2, s, t, dis[500055], ans, rt, op; vector<int> z; int nedge, head[500055 * 2], to[500055 * 2], Next[500055 * 2]; void add(int a, int b) { Next[++nedge] = head[a]; head[a] = nedge; to[nedge] = b; } void add_ne(int a, int b) { add(a, b); add(b, a); } void dfs(int x) { for (int i = head[x]; i; i = Next[i]) { if (to[i] == fa[x]) continue; fa[to[i]] = x; dis[to[i]] = dis[x] + 1; dfs(to[i]); } } int lca(int x, int y) { for (; x != y; x = fa[x]) if (dis[x] < dis[y]) swap(x, y); return x; } void ret() { puts("-1"); exit(0); } void check() { for (int i = (1); i <= (n); i++) { if (a[i] != b[i]) { if (dis[i] > dis[s]) s = i; } } if (s == 0) { wrn(0, ans); exit(0); } for (int i = s; vis[i] = 1, z.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; for (int i = (1); i <= (n); i++) if (a[i] != b[i] && !vis[i]) t = dis[t] < dis[i] ? i : t; if (t) { reverse(z.begin(), z.end()); for (int i = t; vis[i] = 1, z.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; } else t = fa[z.back()]; for (int i = (1); i <= (n); i++) if (a[i] != b[i] && !vis[i]) ret(); rt = lca(s, t); if (z.size() != dis[s] + dis[t] - 2 * dis[rt]) ret(); } void init() { n = read(); for (int i = (1); i <= (n); i++) { a[i] = read(); if (a[i] == 0) s1 = i; } for (int i = (1); i <= (n); i++) { b[i] = read(); if (b[i] == 0) s2 = i; } for (int i = (1); i <= (n - 1); i++) add_ne(read(), read()); dis[0] = -1; dfs(s2); ans = dis[s1]; for (int i = s1; i != s2; i = fa[i]) swap(a[i], a[fa[i]]); } void work() { int p = 0; for (int i = (0); i <= (z.size() - 1); i++) if (b[z[i]] == a[z[0]]) p = i; for (int i = (1); i <= (z.size() - 1); i++) if (b[z[(i + p) % z.size()]] != a[z[i]]) ret(); memset(vis, 0, sizeof(vis)); for (int i = s1; i; i = fa[i]) vis[i] = 1; int cqz = 0; int wzp = z.size(); if (vis[z[0]] || vis[z.back()]) { for (int i = (0); i <= (z.size() - 1); i++) if (!vis[z[i]]) { cqz = i; break; } ans += -cqz + min(cqz + p * (wzp + 1), abs((wzp - p) * (wzp + 1) - cqz)); } else ans += min(p, wzp - p) * (wzp + 1); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (s > t) swap(s, t); wrn(s, t, ans); } signed main() { init(); check(); work(); return 0; }
### Prompt Create a solution in cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline char gc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline int read() { char c = getchar(); int tot = 1; while ((c < '0' || c > '9') && c != '-') c = getchar(); if (c == '-') { tot = -1; c = getchar(); } int sum = 0; while (c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); } return sum * tot; } inline void wr(int x) { if (x < 0) { putchar('-'); wr(-x); return; } if (x >= 10) wr(x / 10); putchar(x % 10 + '0'); } inline void wrn(int x) { wr(x); putchar('\n'); } inline void wri(int x) { wr(x); putchar(' '); } inline void wrn(int x, int y) { wri(x); wrn(y); } inline void wrn(int a, int b, int c) { wri(a); wrn(b, c); } int n, m, fa[500055], vis[500055], a[500055], b[500055], s1, s2, s, t, dis[500055], ans, rt, op; vector<int> z; int nedge, head[500055 * 2], to[500055 * 2], Next[500055 * 2]; void add(int a, int b) { Next[++nedge] = head[a]; head[a] = nedge; to[nedge] = b; } void add_ne(int a, int b) { add(a, b); add(b, a); } void dfs(int x) { for (int i = head[x]; i; i = Next[i]) { if (to[i] == fa[x]) continue; fa[to[i]] = x; dis[to[i]] = dis[x] + 1; dfs(to[i]); } } int lca(int x, int y) { for (; x != y; x = fa[x]) if (dis[x] < dis[y]) swap(x, y); return x; } void ret() { puts("-1"); exit(0); } void check() { for (int i = (1); i <= (n); i++) { if (a[i] != b[i]) { if (dis[i] > dis[s]) s = i; } } if (s == 0) { wrn(0, ans); exit(0); } for (int i = s; vis[i] = 1, z.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; for (int i = (1); i <= (n); i++) if (a[i] != b[i] && !vis[i]) t = dis[t] < dis[i] ? i : t; if (t) { reverse(z.begin(), z.end()); for (int i = t; vis[i] = 1, z.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; } else t = fa[z.back()]; for (int i = (1); i <= (n); i++) if (a[i] != b[i] && !vis[i]) ret(); rt = lca(s, t); if (z.size() != dis[s] + dis[t] - 2 * dis[rt]) ret(); } void init() { n = read(); for (int i = (1); i <= (n); i++) { a[i] = read(); if (a[i] == 0) s1 = i; } for (int i = (1); i <= (n); i++) { b[i] = read(); if (b[i] == 0) s2 = i; } for (int i = (1); i <= (n - 1); i++) add_ne(read(), read()); dis[0] = -1; dfs(s2); ans = dis[s1]; for (int i = s1; i != s2; i = fa[i]) swap(a[i], a[fa[i]]); } void work() { int p = 0; for (int i = (0); i <= (z.size() - 1); i++) if (b[z[i]] == a[z[0]]) p = i; for (int i = (1); i <= (z.size() - 1); i++) if (b[z[(i + p) % z.size()]] != a[z[i]]) ret(); memset(vis, 0, sizeof(vis)); for (int i = s1; i; i = fa[i]) vis[i] = 1; int cqz = 0; int wzp = z.size(); if (vis[z[0]] || vis[z.back()]) { for (int i = (0); i <= (z.size() - 1); i++) if (!vis[z[i]]) { cqz = i; break; } ans += -cqz + min(cqz + p * (wzp + 1), abs((wzp - p) * (wzp + 1) - cqz)); } else ans += min(p, wzp - p) * (wzp + 1); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (s > t) swap(s, t); wrn(s, t, ans); } signed main() { init(); check(); work(); return 0; } ```
#include <bits/stdc++.h> using namespace std; int read(); int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } const int _SIZE = 1 << 22; char ibuf[_SIZE], *iS = ibuf, *iT = ibuf; int read() { int x = 0, f = 1; char c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (!isdigit(c)) f = (c == '-') ? -1 : f, c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (isdigit(c)) x = x * 10 + c - '0', c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); return x * f; }
### Prompt Your challenge is to write a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int read(); int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } const int _SIZE = 1 << 22; char ibuf[_SIZE], *iS = ibuf, *iT = ibuf; int read() { int x = 0, f = 1; char c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (!isdigit(c)) f = (c == '-') ? -1 : f, c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (isdigit(c)) x = x * 10 + c - '0', c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); return x * f; } ```
#include <bits/stdc++.h> int n, A[200001], B[200001], head[200001], nxt[400001], b[400001], k, S, T, pre[200001], next[200001]; int num[200001], top, tem1[200001], tem2[200001]; void push(int s, int t) { nxt[++k] = head[s]; head[s] = k; b[k] = t; } int dfs(int x, int f, int dis = 0) { if (x == T) return dis; for (int i = head[x]; i; i = nxt[i]) if (b[i] != f) { int u = dfs(b[i], x, dis + 1); if (~u) return u; } return -1; } bool getpath(int x, int f, int end) { num[++top] = x; if (x == end) return 1; for (int i = head[x]; i; i = nxt[i]) if (b[i] != f && getpath(b[i], x, end)) return 1; --top; return 0; } bool vis[200001]; int d[200001]; int check(int len) { int p = -1; for (int i = 0; i < len; i++) if (tem2[i] == tem1[0]) p = i; for (int i = 0; i < len; i++) if (tem2[(i + p) % len] != tem1[i]) { puts("-1"); exit(0); } return std::min(p, len - p); } int getdis(int x, int f, int dis = 0) { if (!vis[x]) return dis; for (int i = head[x]; i; i = nxt[i]) if (b[i] != f) { int u = getdis(b[i], x, dis + 1); if (~u) return u; } return -1; } void addone(int x, int f) { if (!vis[x]) { if (d[x] > 1) { puts("-1"); exit(0); } vis[f] = 0; A[f] = B[f] = 0; return; } for (int i = head[x]; i; i = nxt[i]) if (b[i] != f) { addone(b[i], x); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", A + i); for (int i = 1; i <= n; i++) scanf("%d", B + i); for (int i = 1; i <= n; i++) pre[i] = next[i] = -1; for (int i = 1, u, v; i < n; i++) scanf("%d%d", &u, &v), push(u, v), push(v, u); bool cando = 1; for (int i = 1; i <= n; i++) if (A[i] != B[i] || !A[i]) { if (!A[i]) S = i; if (!B[i]) T = i; for (int j = head[i]; j; j = nxt[j]) if (A[b[j]] == B[i] && B[i]) pre[i] = b[j], next[b[j]] = i; if (!~pre[i] && i != T) cando = 0; } else vis[i] = 1; int tem = S; long long ans = 0; int pp1, pp2; while (~pre[tem]) { vis[tem] = 1; ++ans; tem = pre[tem]; } pp1 = tem; A[tem] = 0; tem = T; while (~next[tem]) { vis[tem] = 1; ++ans; tem = next[tem]; } B[tem] = 0; pp2 = tem; if (pp1 != pp2 && !vis[pp1] && !vis[pp2]) { int cnt = 0; for (int i = 1; i <= n; i++) if (!vis[i]) ++cnt; if (cnt == 2) { if (pp1 > pp2) std::swap(pp1, pp2); printf("%d %d %d\n", pp1, pp2, ans + 1); return 0; } } bool bb = 0; if ((tem == S && vis[S]) || (S == T)) { vis[S] = 1; bool over = 1; for (int i = 1; i <= n; i++) if (!vis[i]) over = 0; if (over) { printf("0 %d\n", dfs(S, 0)); return 0; } else { bb = 1; int cnt = 0; for (int i = 1; i <= n; i++) if (!vis[i]) for (int j = head[i]; j; j = nxt[j]) if (!vis[b[j]]) ++d[b[j]]; for (int i = 1; i <= n; i++) if (!vis[i]) { if (d[i] > 2) { puts("-1"); return 0; } if (d[i] == 1) ++cnt; } if (cnt > 4) { puts("-1"); return 0; } if (cnt == 4) { int node = -1; for (int i = 1; i <= n; i++) if (vis[i]) { int cnt = 0; for (int j = head[i]; j; j = nxt[j]) if (d[b[j]] == 1) ++cnt; if (cnt == 2) node = i; } if (!~node) { puts("-1"); return 0; } vis[node] = 0; A[node] = B[node] = 0; } else addone(S, 0); ans = getdis(S, 0) + getdis(T, 0); memset(d, 0, sizeof d); } } for (int i = 1; i <= n; i++) if (!vis[i]) for (int j = head[i]; j; j = nxt[j]) if (!vis[b[j]]) ++d[b[j]]; int p1 = -1, p2 = -1; for (int i = 1; i <= n; i++) if (!vis[i]) { if (d[i] > 2 || !d[i]) { puts("-1"); return 0; } if (d[i] == 1) { if (!~p1) p1 = i; else if (!~p2) p2 = i; else { puts("-1"); return 0; } } } if (!~p2) { puts("-1"); return 0; } getpath(p1, 0, p2); int added = 1; int pos1 = -1, pos2 = -1; for (int i = 1; i <= top; i++) if (A[num[i]]) tem1[i - added] = A[num[i]]; else added++, pos1 = i - 1; added = 1; for (int i = 1; i <= top; i++) if (B[num[i]]) tem2[i - added] = B[num[i]]; else added++, pos2 = i - 1; long long fin = 1e18; fin = std::min(fin, 1ll * top * check(top - 1) + abs(pos2 - pos1)); if (pos1 < pos2) { int orig = tem1[top - 2]; for (int i = top - 2; i; i--) tem1[i] = tem1[i - 1]; tem1[0] = orig; } else if (pos1 > pos2) { int orig = tem1[0]; for (int i = 0; i < top - 2; i++) tem1[i] = tem1[i + 1]; tem1[top - 2] = orig; } fin = std::min(fin, 1ll * top * check(top - 1) + top - abs(pos2 - pos1)); printf("%d %d %d\n", p1, p2, ans + fin); }
### Prompt Create a solution in cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> int n, A[200001], B[200001], head[200001], nxt[400001], b[400001], k, S, T, pre[200001], next[200001]; int num[200001], top, tem1[200001], tem2[200001]; void push(int s, int t) { nxt[++k] = head[s]; head[s] = k; b[k] = t; } int dfs(int x, int f, int dis = 0) { if (x == T) return dis; for (int i = head[x]; i; i = nxt[i]) if (b[i] != f) { int u = dfs(b[i], x, dis + 1); if (~u) return u; } return -1; } bool getpath(int x, int f, int end) { num[++top] = x; if (x == end) return 1; for (int i = head[x]; i; i = nxt[i]) if (b[i] != f && getpath(b[i], x, end)) return 1; --top; return 0; } bool vis[200001]; int d[200001]; int check(int len) { int p = -1; for (int i = 0; i < len; i++) if (tem2[i] == tem1[0]) p = i; for (int i = 0; i < len; i++) if (tem2[(i + p) % len] != tem1[i]) { puts("-1"); exit(0); } return std::min(p, len - p); } int getdis(int x, int f, int dis = 0) { if (!vis[x]) return dis; for (int i = head[x]; i; i = nxt[i]) if (b[i] != f) { int u = getdis(b[i], x, dis + 1); if (~u) return u; } return -1; } void addone(int x, int f) { if (!vis[x]) { if (d[x] > 1) { puts("-1"); exit(0); } vis[f] = 0; A[f] = B[f] = 0; return; } for (int i = head[x]; i; i = nxt[i]) if (b[i] != f) { addone(b[i], x); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", A + i); for (int i = 1; i <= n; i++) scanf("%d", B + i); for (int i = 1; i <= n; i++) pre[i] = next[i] = -1; for (int i = 1, u, v; i < n; i++) scanf("%d%d", &u, &v), push(u, v), push(v, u); bool cando = 1; for (int i = 1; i <= n; i++) if (A[i] != B[i] || !A[i]) { if (!A[i]) S = i; if (!B[i]) T = i; for (int j = head[i]; j; j = nxt[j]) if (A[b[j]] == B[i] && B[i]) pre[i] = b[j], next[b[j]] = i; if (!~pre[i] && i != T) cando = 0; } else vis[i] = 1; int tem = S; long long ans = 0; int pp1, pp2; while (~pre[tem]) { vis[tem] = 1; ++ans; tem = pre[tem]; } pp1 = tem; A[tem] = 0; tem = T; while (~next[tem]) { vis[tem] = 1; ++ans; tem = next[tem]; } B[tem] = 0; pp2 = tem; if (pp1 != pp2 && !vis[pp1] && !vis[pp2]) { int cnt = 0; for (int i = 1; i <= n; i++) if (!vis[i]) ++cnt; if (cnt == 2) { if (pp1 > pp2) std::swap(pp1, pp2); printf("%d %d %d\n", pp1, pp2, ans + 1); return 0; } } bool bb = 0; if ((tem == S && vis[S]) || (S == T)) { vis[S] = 1; bool over = 1; for (int i = 1; i <= n; i++) if (!vis[i]) over = 0; if (over) { printf("0 %d\n", dfs(S, 0)); return 0; } else { bb = 1; int cnt = 0; for (int i = 1; i <= n; i++) if (!vis[i]) for (int j = head[i]; j; j = nxt[j]) if (!vis[b[j]]) ++d[b[j]]; for (int i = 1; i <= n; i++) if (!vis[i]) { if (d[i] > 2) { puts("-1"); return 0; } if (d[i] == 1) ++cnt; } if (cnt > 4) { puts("-1"); return 0; } if (cnt == 4) { int node = -1; for (int i = 1; i <= n; i++) if (vis[i]) { int cnt = 0; for (int j = head[i]; j; j = nxt[j]) if (d[b[j]] == 1) ++cnt; if (cnt == 2) node = i; } if (!~node) { puts("-1"); return 0; } vis[node] = 0; A[node] = B[node] = 0; } else addone(S, 0); ans = getdis(S, 0) + getdis(T, 0); memset(d, 0, sizeof d); } } for (int i = 1; i <= n; i++) if (!vis[i]) for (int j = head[i]; j; j = nxt[j]) if (!vis[b[j]]) ++d[b[j]]; int p1 = -1, p2 = -1; for (int i = 1; i <= n; i++) if (!vis[i]) { if (d[i] > 2 || !d[i]) { puts("-1"); return 0; } if (d[i] == 1) { if (!~p1) p1 = i; else if (!~p2) p2 = i; else { puts("-1"); return 0; } } } if (!~p2) { puts("-1"); return 0; } getpath(p1, 0, p2); int added = 1; int pos1 = -1, pos2 = -1; for (int i = 1; i <= top; i++) if (A[num[i]]) tem1[i - added] = A[num[i]]; else added++, pos1 = i - 1; added = 1; for (int i = 1; i <= top; i++) if (B[num[i]]) tem2[i - added] = B[num[i]]; else added++, pos2 = i - 1; long long fin = 1e18; fin = std::min(fin, 1ll * top * check(top - 1) + abs(pos2 - pos1)); if (pos1 < pos2) { int orig = tem1[top - 2]; for (int i = top - 2; i; i--) tem1[i] = tem1[i - 1]; tem1[0] = orig; } else if (pos1 > pos2) { int orig = tem1[0]; for (int i = 0; i < top - 2; i++) tem1[i] = tem1[i + 1]; tem1[top - 2] = orig; } fin = std::min(fin, 1ll * top * check(top - 1) + top - abs(pos2 - pos1)); printf("%d %d %d\n", p1, p2, ans + fin); } ```
#include <bits/stdc++.h> using namespace std; int read(); int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } const int _SIZE = 1 << 22; char ibuf[_SIZE], *iS = ibuf, *iT = ibuf; int read() { int x = 0, f = 1; char c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (!isdigit(c)) f = (c == '-') ? -1 : f, c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (isdigit(c)) x = x * 10 + c - '0', c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); return x * f; }
### Prompt Please create a solution in cpp to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int read(); int n; int a[200005], b[200005], c[200005], bk[200005]; int hd[200005], nx[400005], to[400005], cnt; void add(int f, int t) { nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t; } int fa[200005], dep[200005]; void dfs1(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) dep[v] = dep[fa[v] = u] + 1, dfs1(v); } bool check1() { for (int i = 1; i <= n; ++i) c[i] = b[i]; int u = a[1]; while (fa[u]) swap(c[u], c[fa[u]]), u = fa[u]; for (int i = 1; i <= n; ++i) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idcnt; void fail() { puts("-1"), exit(0); } void get(int u, int id) { if (id >= 2 || (id == 1 && fa[st[0][0]] != fa[u])) fail(); st[id].push_back(u); while (1) { int v = 0; for (int i = hd[u]; i; i = nx[i]) if (to[i] != fa[u] && c[to[i]] != to[i]) v ? fail() : (v = to[i], void()); if (!v) break; st[id].push_back(u = v); } } void dfs2(int u) { for (int i = hd[u], v; i; i = nx[i]) if ((v = to[i]) != fa[u]) (c[v] != v) ? get(v, idcnt++) : dfs2(v); } int p[200005], q[200005], len; int M(int x) { return x >= len ? x - len : x; } int getdis(int u, int v) { int rt = 0; while (u != v) (dep[u] < dep[v]) ? swap(u, v) : void(), ++rt, u = fa[u]; return rt; } void work() { for (int i = 1; i <= n; ++i) q[i] = -1; for (int i = 0; i < st[0].size(); ++i) p[len] = c[st[0][i]], q[st[0][i]] = len, ++len; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (st[1].size()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); long long dis = q[p[0]]; for (int i = 1; i < len; ++i) if (M(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; ++i) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); printf("%d %d %lld\n", ru, rv, dis + getdis(a[1], rw) + dep[rw]); return; } dis = q[t] >= st[0].size() ? min((dis - 1) * (len + 1) + (q[t] + 1), 1ll * M(len - dis) * (len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); printf("%d %d %lld\n", ru, rv, dis + dep[rw] + getdis(a[1], t)); } int main() { n = read(); for (int i = 1; i <= n; ++i) bk[a[i] = read() + 1] = i; for (int i = 1; i <= n; ++i) b[a[i]] = read() + 1; for (int i = 1, u, v; i < n; ++i) u = a[read()], v = a[read()], add(u, v), add(v, u); for (int i = 1; i <= n; ++i) a[b[i]] = i; dfs1(1); if (check1()) return printf("0 %d\n", dep[a[1]]), 0; dfs2(1), work(); return 0; } const int _SIZE = 1 << 22; char ibuf[_SIZE], *iS = ibuf, *iT = ibuf; int read() { int x = 0, f = 1; char c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (!isdigit(c)) f = (c == '-') ? -1 : f, c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); while (isdigit(c)) x = x * 10 + c - '0', c = (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), (iS == iT ? EOF : *iS++) : *iS++); return x * f; } ```
#include <bits/stdc++.h> using namespace std; int v1[200500], v2[200500], v3[200500], s, t, head[200500], cnt, is[200500], fr[200500], ct, st[200500], fg, s1, s2, s3, s4, s5, a, b, st2[200500], ct2, vl[200500], c1, ins[200500], n, fr2[200500], is2[200500], d1, is3[200500]; struct edge { int t, next; } ed[200500 * 2]; void adde(int f, int t) { ed[++cnt] = (edge){t, head[f]}; head[f] = cnt; ed[++cnt] = (edge){f, head[t]}; head[t] = cnt; } void dfs(int u, int fa) { if (!fg) st[++ct] = u; if (u == t) fg = 1; for (int i = head[u]; i; i = ed[i].next) if (ed[i].t != fa) dfs(ed[i].t, u); if (!fg) ct--; } bool check(int l, int r) { t = r; ct = 0; fg = 0; dfs(l, 0); for (int i = 1; i <= n; i++) ins[i] = 0; for (int i = 1; i <= ct; i++) ins[st[i]] = 1; for (int i = 1; i <= n; i++) if (is[i] && !ins[i]) return 0; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &v1[i]); if (!v1[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &v2[i]); if (!v2[i]) t = i; } for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), adde(a, b); dfs(s, 0); s3 = s, s4 = t; for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; int fg1 = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { fg1 = 1; is[i] = 1; for (int j = head[i]; j; j = ed[j].next) fr[ed[j].t]++; } if (!fg1) { printf("0 %d\n", ct - 1); return 0; } for (int i = 1; i <= n; i++) if (is[i] && fr[i] <= 1) vl[++c1] = i; if (c1 > 4) { printf("-1\n"); return 0; } for (int i = 1; i <= c1 && fg1 == 1; i++) for (int j = i + 1; j <= c1; j++) if (check(vl[i], vl[j])) { s1 = vl[i], s2 = vl[j]; fg1 = 2; break; } t = s2; ct = fg = 0; dfs(s1, 0); for (int i = 1; i <= ct; i++) is3[st[i]] = 1; if (fg1 == 1) { printf("-1\n"); return 0; } int v4 = 0; for (int i = 1; i <= ct; i++) if (!is[st[i]]) { if (v4) { printf("-1\n"); return 0; } v4 = st[i]; } if (!v4) { t = s1; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s1 = v4; else { t = s2; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s2 = v4; else { int st = 1; for (int i = head[s]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st = 2; if (s1 == s) s1 = v4; else s2 = v4; } if (st == 1) { int st2 = 0, st3 = (s1 == s ? s2 : s1); for (int i = head[st3]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st2 = 1; if (s1 == s) s2 = v4; else s1 = v4; } if (!st2) { printf("-1\n"); return 0; } } } } } else { t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= ct; i++) if (is3[st[i]]) { v4 = st[i]; break; } } t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; long long as = ct - 1; t = s2; ct = 0; fg = 0; dfs(s1, 0); int ct1 = 0, ct2 = 0, fg2 = -1, tp = 0; for (int i = 1; i <= ct; i++) fr2[v2[st[i]]] = i, is2[st[i]] = 1; for (int i = 1; i <= ct; i++) { if (!v3[st[i]]) continue; int nt = fr2[v3[st[i]]]; fr2[v3[st[i]]] = 0; if (!nt) { printf("-1\n"); return 0; } int st = i - nt + (i < nt ? ct : 0); if (fg2 == -1) fg2 = st, ct1 = 1; else { if (fg2 == st) ct1++; else if (fg2 == st - 1) ct2++; else if (fg2 == st + 1) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1; ct1 = 1, fg2--; } else if (fg2 == 0 && st + 1 == ct) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1, ct1 = 1, fg2 = ct - 1; } else if (st == 0 && fg2 == ct - 1) ct2++; else { printf("-1\n"); return 0; } } } for (int i = 1; i <= ct; i++) v3[st[i]] = v2[st[i]]; long long as1 = 1ll * ct1 * fg2 + 1ll * ct2 * (fg2 + 1), as2 = 1ll * ct1 * (ct - fg2) + 1ll * ct2 * (ct - fg2 - 1); if (as2 < as1) as1 = as2; as += as1; for (int i = 1; i <= n; i++) if (fr2[v2[i]]) s5 = i; v3[s5] = 0; t = s4; ct = 0; fg = 0; dfs(s5, 0); for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { printf("-1\n"); return 0; } as += ct - 1; if (s1 > s2) s1 ^= s2 ^= s1 ^= s2; printf("%d %d %lld\n", s1, s2, as); }
### Prompt Please formulate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int v1[200500], v2[200500], v3[200500], s, t, head[200500], cnt, is[200500], fr[200500], ct, st[200500], fg, s1, s2, s3, s4, s5, a, b, st2[200500], ct2, vl[200500], c1, ins[200500], n, fr2[200500], is2[200500], d1, is3[200500]; struct edge { int t, next; } ed[200500 * 2]; void adde(int f, int t) { ed[++cnt] = (edge){t, head[f]}; head[f] = cnt; ed[++cnt] = (edge){f, head[t]}; head[t] = cnt; } void dfs(int u, int fa) { if (!fg) st[++ct] = u; if (u == t) fg = 1; for (int i = head[u]; i; i = ed[i].next) if (ed[i].t != fa) dfs(ed[i].t, u); if (!fg) ct--; } bool check(int l, int r) { t = r; ct = 0; fg = 0; dfs(l, 0); for (int i = 1; i <= n; i++) ins[i] = 0; for (int i = 1; i <= ct; i++) ins[st[i]] = 1; for (int i = 1; i <= n; i++) if (is[i] && !ins[i]) return 0; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &v1[i]); if (!v1[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &v2[i]); if (!v2[i]) t = i; } for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), adde(a, b); dfs(s, 0); s3 = s, s4 = t; for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; int fg1 = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { fg1 = 1; is[i] = 1; for (int j = head[i]; j; j = ed[j].next) fr[ed[j].t]++; } if (!fg1) { printf("0 %d\n", ct - 1); return 0; } for (int i = 1; i <= n; i++) if (is[i] && fr[i] <= 1) vl[++c1] = i; if (c1 > 4) { printf("-1\n"); return 0; } for (int i = 1; i <= c1 && fg1 == 1; i++) for (int j = i + 1; j <= c1; j++) if (check(vl[i], vl[j])) { s1 = vl[i], s2 = vl[j]; fg1 = 2; break; } t = s2; ct = fg = 0; dfs(s1, 0); for (int i = 1; i <= ct; i++) is3[st[i]] = 1; if (fg1 == 1) { printf("-1\n"); return 0; } int v4 = 0; for (int i = 1; i <= ct; i++) if (!is[st[i]]) { if (v4) { printf("-1\n"); return 0; } v4 = st[i]; } if (!v4) { t = s1; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s1 = v4; else { t = s2; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s2 = v4; else { int st = 1; for (int i = head[s]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st = 2; if (s1 == s) s1 = v4; else s2 = v4; } if (st == 1) { int st2 = 0, st3 = (s1 == s ? s2 : s1); for (int i = head[st3]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st2 = 1; if (s1 == s) s2 = v4; else s1 = v4; } if (!st2) { printf("-1\n"); return 0; } } } } } else { t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= ct; i++) if (is3[st[i]]) { v4 = st[i]; break; } } t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; long long as = ct - 1; t = s2; ct = 0; fg = 0; dfs(s1, 0); int ct1 = 0, ct2 = 0, fg2 = -1, tp = 0; for (int i = 1; i <= ct; i++) fr2[v2[st[i]]] = i, is2[st[i]] = 1; for (int i = 1; i <= ct; i++) { if (!v3[st[i]]) continue; int nt = fr2[v3[st[i]]]; fr2[v3[st[i]]] = 0; if (!nt) { printf("-1\n"); return 0; } int st = i - nt + (i < nt ? ct : 0); if (fg2 == -1) fg2 = st, ct1 = 1; else { if (fg2 == st) ct1++; else if (fg2 == st - 1) ct2++; else if (fg2 == st + 1) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1; ct1 = 1, fg2--; } else if (fg2 == 0 && st + 1 == ct) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1, ct1 = 1, fg2 = ct - 1; } else if (st == 0 && fg2 == ct - 1) ct2++; else { printf("-1\n"); return 0; } } } for (int i = 1; i <= ct; i++) v3[st[i]] = v2[st[i]]; long long as1 = 1ll * ct1 * fg2 + 1ll * ct2 * (fg2 + 1), as2 = 1ll * ct1 * (ct - fg2) + 1ll * ct2 * (ct - fg2 - 1); if (as2 < as1) as1 = as2; as += as1; for (int i = 1; i <= n; i++) if (fr2[v2[i]]) s5 = i; v3[s5] = 0; t = s4; ct = 0; fg = 0; dfs(s5, 0); for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { printf("-1\n"); return 0; } as += ct - 1; if (s1 > s2) s1 ^= s2 ^= s1 ^= s2; printf("%d %d %lld\n", s1, s2, as); } ```
#include <bits/stdc++.h> using namespace std; struct Edge { int to; int nxt; } e[400005]; int n, m, x, edgenum, head[200005], pa[200005], pa2[200005], a[200005], b[200005], d[200005], r1, r2; int st[200005], top, sta[200005], top2, tmp[200005], top3; bool flag[200005]; void add(int u, int v) { e[++edgenum].to = v; e[edgenum].nxt = head[u]; head[u] = edgenum; } void dfs(int node) { for (int hd = head[node]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[node]) continue; if (flag[to]) continue; pa[to] = node; dfs(to); } } void dfs2(int node) { flag[node] = 1; sta[++top2] = node; for (int hd = head[node]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa2[node]) continue; if (a[to] == b[to]) continue; pa2[to] = node; dfs2(to); } } long long solve() { top = 0; int now = r1; long long ans = 0; while (now != x) { st[++top] = now; a[now] = a[pa[now]]; a[now = pa[now]] = 0; ans++; } for (int hd = head[x]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[x]) continue; if (a[to] != b[to]) { top2 = 0; dfs2(to); break; } } int s = 0; for (int i = 1; i <= top2; i++) { if (a[sta[i]] == b[sta[1]]) { s = i; break; } } ans += 1ll * (top2 + 1) * min(s - 1, top2 - s + 1); for (int i = top; i >= 1; i--) { a[pa[st[i]]] = a[st[i]]; a[st[i]] = 0; } return ans; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) r1 = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) r2 = i; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } dfs(r2); x = r1; while (x != r2) { a[x] = a[pa[x]]; st[++top] = x; a[x = pa[x]] = 0; } for (int i = 1; i < n; i++) { int u = e[i * 2 - 1].to; int v = e[i * 2].to; if (a[u] != b[u] && a[v] != b[v]) d[u]++, d[v]++; } int num = 0; x = 0; for (int i = 1; i <= n; i++) { if (a[i] != b[i]) { x = i; if (d[i] > 2) return puts("-1"), 0; if (d[i] == 1) num++; if (d[i] == 0) num += 2; } } if (!x) { printf("0 %d\n", top); return 0; } if (num != 4 && num != 2) return puts("-1"), 0; while (a[x] != b[x]) x = pa[x]; int num2 = 0; for (int hd = head[x]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[x]) continue; if (a[to] != b[to]) num2++; } if (num == 4 && num2 != 2) return puts("-1"), 0; if (num == 2 && num2 != 1) return puts("-1"), 0; int u = 0, v = 0; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && ((d[i] == 1 && (num == 4 ? pa[i] != x : 1)) || d[i] == 0)) { if (!u) u = pa[i] == x && num == 2 ? x : i; else v = pa[i] == x && num == 2 ? x : i; } } add(u, v); add(v, u); for (int hd = head[x]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[x]) continue; if (a[to] != b[to]) { dfs2(to); break; } } int s = 0; for (int i = 1; i <= top2; i++) { if (a[sta[i]] == b[sta[1]]) { s = i; break; } } for (int i = 1; i <= top2; i++) { if (a[sta[(s + i - 2) % top2 + 1]] != b[sta[i]]) return puts("-1"), 0; } printf("%d %d ", min(u, v), max(u, v)); int now = x; while (now != r2) { tmp[++top3] = now; now = pa[now]; } now = r1; while (!flag[now] && now != r2) now = pa[now]; if (now == r2) { long long ans = top3; while (top3) { int x = tmp[top3--]; if (x != st[top]) st[++top] = x; else top--; } printf("%lld\n", ans + top + 1ll * (top2 + 1) * min(s - 1, top2 - s + 1)); return 0; } for (int i = top; i >= 1; i--) { a[pa[st[i]]] = a[st[i]]; a[st[i]] = 0; } long long ans = 0; while (r1 != now) { a[r1] = a[pa[r1]]; a[r1 = pa[r1]] = 0; ans++; } for (int i = top3; i >= 1; i--) { b[pa[tmp[i]]] = b[tmp[i]]; b[tmp[i]] = 0; ans++; } memset(flag, 0, sizeof(flag)); flag[now] = 1; dfs(r2); long long res = 1e18; for (int hd = head[now]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (pa[to] != now) { pa[now] = to; res = min(res, ans + solve()); } } printf("%lld\n", res); return 0; }
### Prompt Construct a CPP code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct Edge { int to; int nxt; } e[400005]; int n, m, x, edgenum, head[200005], pa[200005], pa2[200005], a[200005], b[200005], d[200005], r1, r2; int st[200005], top, sta[200005], top2, tmp[200005], top3; bool flag[200005]; void add(int u, int v) { e[++edgenum].to = v; e[edgenum].nxt = head[u]; head[u] = edgenum; } void dfs(int node) { for (int hd = head[node]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[node]) continue; if (flag[to]) continue; pa[to] = node; dfs(to); } } void dfs2(int node) { flag[node] = 1; sta[++top2] = node; for (int hd = head[node]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa2[node]) continue; if (a[to] == b[to]) continue; pa2[to] = node; dfs2(to); } } long long solve() { top = 0; int now = r1; long long ans = 0; while (now != x) { st[++top] = now; a[now] = a[pa[now]]; a[now = pa[now]] = 0; ans++; } for (int hd = head[x]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[x]) continue; if (a[to] != b[to]) { top2 = 0; dfs2(to); break; } } int s = 0; for (int i = 1; i <= top2; i++) { if (a[sta[i]] == b[sta[1]]) { s = i; break; } } ans += 1ll * (top2 + 1) * min(s - 1, top2 - s + 1); for (int i = top; i >= 1; i--) { a[pa[st[i]]] = a[st[i]]; a[st[i]] = 0; } return ans; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) r1 = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) r2 = i; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } dfs(r2); x = r1; while (x != r2) { a[x] = a[pa[x]]; st[++top] = x; a[x = pa[x]] = 0; } for (int i = 1; i < n; i++) { int u = e[i * 2 - 1].to; int v = e[i * 2].to; if (a[u] != b[u] && a[v] != b[v]) d[u]++, d[v]++; } int num = 0; x = 0; for (int i = 1; i <= n; i++) { if (a[i] != b[i]) { x = i; if (d[i] > 2) return puts("-1"), 0; if (d[i] == 1) num++; if (d[i] == 0) num += 2; } } if (!x) { printf("0 %d\n", top); return 0; } if (num != 4 && num != 2) return puts("-1"), 0; while (a[x] != b[x]) x = pa[x]; int num2 = 0; for (int hd = head[x]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[x]) continue; if (a[to] != b[to]) num2++; } if (num == 4 && num2 != 2) return puts("-1"), 0; if (num == 2 && num2 != 1) return puts("-1"), 0; int u = 0, v = 0; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && ((d[i] == 1 && (num == 4 ? pa[i] != x : 1)) || d[i] == 0)) { if (!u) u = pa[i] == x && num == 2 ? x : i; else v = pa[i] == x && num == 2 ? x : i; } } add(u, v); add(v, u); for (int hd = head[x]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (to == pa[x]) continue; if (a[to] != b[to]) { dfs2(to); break; } } int s = 0; for (int i = 1; i <= top2; i++) { if (a[sta[i]] == b[sta[1]]) { s = i; break; } } for (int i = 1; i <= top2; i++) { if (a[sta[(s + i - 2) % top2 + 1]] != b[sta[i]]) return puts("-1"), 0; } printf("%d %d ", min(u, v), max(u, v)); int now = x; while (now != r2) { tmp[++top3] = now; now = pa[now]; } now = r1; while (!flag[now] && now != r2) now = pa[now]; if (now == r2) { long long ans = top3; while (top3) { int x = tmp[top3--]; if (x != st[top]) st[++top] = x; else top--; } printf("%lld\n", ans + top + 1ll * (top2 + 1) * min(s - 1, top2 - s + 1)); return 0; } for (int i = top; i >= 1; i--) { a[pa[st[i]]] = a[st[i]]; a[st[i]] = 0; } long long ans = 0; while (r1 != now) { a[r1] = a[pa[r1]]; a[r1 = pa[r1]] = 0; ans++; } for (int i = top3; i >= 1; i--) { b[pa[tmp[i]]] = b[tmp[i]]; b[tmp[i]] = 0; ans++; } memset(flag, 0, sizeof(flag)); flag[now] = 1; dfs(r2); long long res = 1e18; for (int hd = head[now]; hd; hd = e[hd].nxt) { int to = e[hd].to; if (pa[to] != now) { pa[now] = to; res = min(res, ans + solve()); } } printf("%lld\n", res); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MaxN = 200010, MaxM = 400010; const long long inf = 1ll << 60; class Graph { public: int en[MaxN], next[MaxM], to[MaxM], tot; void add_edge(int x, int y) { next[++tot] = en[x]; en[x] = tot; to[tot] = y; } } G; int n, a[MaxN], b[MaxN]; int edge_u, edge_v; bool diff[MaxN]; long long step; inline bool check() { for (int i = 1; i <= n; ++i) if (a[i] != b[i]) return 0; return 1; } int cycle[MaxN], ctot; bool vis[MaxN], flag; int father[MaxN], depth[MaxN]; void dfs_init(int now) { vis[now] = 1; for (int i = G.en[now]; i; i = G.next[i]) if (!vis[G.to[i]]) { father[G.to[i]] = now; depth[G.to[i]] = depth[now] + 1; dfs_init(G.to[i]); } } int get_lca(int u, int v) { while (u != v) { if (depth[u] > depth[v]) u = father[u]; else v = father[v]; } return u; } int get_dist(int l, int u) { return depth[u] - depth[l]; } void dfs_edge(int now) { vis[now] = 1; int deg = 0; for (int i = G.en[now]; i; i = G.next[i]) if (diff[G.to[i]]) { ++deg; if (!vis[G.to[i]]) dfs_edge(G.to[i]); } if (deg == 1) { if (edge_u) edge_v = now; else edge_u = now; } if (deg > 2) flag = 1; } void dfs_cycle(int now) { cycle[++ctot] = now; vis[now] = 1; for (int i = G.en[now]; i; i = G.next[i]) if (!vis[G.to[i]] && diff[G.to[i]]) dfs_cycle(G.to[i]); } int get_deg(int u) { int deg = 0; for (int i = G.en[u]; i; i = G.next[i]) deg += diff[G.to[i]]; return deg; } int pos[MaxN]; void solve_cycle(int in, int out) { for (int u = 1; u <= n; ++u) if (get_deg(u) == 2) diff[u] = 1; memset(vis, 0, sizeof(vis)); ; dfs_edge(in); if (flag) return; if (edge_u > edge_v) swap(edge_u, edge_v); G.add_edge(edge_u, edge_v); G.add_edge(edge_v, edge_u); memset(vis, 0, sizeof(vis)); ; dfs_cycle(in); if (!vis[out]) return; int node = 0; for (int i = 1; i <= ctot; ++i) if (cycle[i] != out) { pos[b[cycle[i]]] = ++node; } int delta = pos[a[cycle[2]]] - 1; for (int i = 2; i <= ctot; ++i) { int tmp = pos[a[cycle[i]]] - i + 1; if (tmp < 0) tmp += ctot - 1; if (tmp != delta) return; } int post = 0; for (int i = 1; i <= ctot; ++i) if (cycle[i] == out) post = i; long long now = inf, st; st = 1ll * delta * ctot - (post - 1); if (st < 0) st = -st; now = min(now, st); st = 1ll * (ctot - delta - 1) * ctot + (post - 1); if (st < 0) st = -st; now = min(now, st); step += now; for (int i = 1; i <= ctot; ++i) a[cycle[i]] = b[cycle[i]]; } void go(int& s, int* a, int* b) { while (true) { int pos = 0, deg = 0; for (int i = G.en[s]; i; i = G.next[i]) if (a[G.to[i]] != b[G.to[i]]) { ++deg; if (a[G.to[i]] == b[s]) pos = G.to[i]; } if (!pos || (deg != 1)) return; swap(a[s], a[pos]); s = pos; ++step; } } int bfs(int& s) { static int q[MaxN], dist[MaxN]; int l = 0, r = 0; memset(dist, 63, sizeof(dist)); q[++r] = s; dist[s] = 0; while (l != r) { int u = q[++l]; for (int i = G.en[u]; i; i = G.next[i]) if (dist[G.to[i]] > dist[u] + 1) { dist[G.to[i]] = dist[u] + 1; q[++r] = G.to[i]; if (diff[G.to[i]]) { s = u; return dist[u]; } } } return -1; } int main() { int s, t; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", a + i); if (a[i] == 0) s = i; } for (int i = 1; i <= n; ++i) { scanf("%d", b + i); if (b[i] == 0) t = i; } for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); G.add_edge(u, v); G.add_edge(v, u); } int ss = s, tt = t; go(s, a, b); if (check()) { printf("0 %I64d\n", step); return 0; } go(t, b, a); if ((a[t] == b[s]) && (a[s] == b[t])) { swap(a[t], a[s]); if (check()) { printf("%d %d %I64d\n", min(s, t), max(s, t), step + 1); return 0; } swap(a[t], a[s]); } int root = 0; for (int i = 1; i <= n; ++i) { diff[i] = (a[i] != b[i]); if (diff[i]) root = i; } memset(vis, 0, sizeof(vis)); ; dfs_init(root); if (a[s] == b[s]) { int l = get_lca(ss, tt); step = get_dist(l, ss) + get_dist(l, tt); step += 2 * bfs(l); solve_cycle(l, l); } else solve_cycle(s, t); if (!check()) printf("-1\n"); else printf("%d %d %I64d\n", edge_u, edge_v, step); return 0; }
### Prompt In CPP, your task is to solve the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MaxN = 200010, MaxM = 400010; const long long inf = 1ll << 60; class Graph { public: int en[MaxN], next[MaxM], to[MaxM], tot; void add_edge(int x, int y) { next[++tot] = en[x]; en[x] = tot; to[tot] = y; } } G; int n, a[MaxN], b[MaxN]; int edge_u, edge_v; bool diff[MaxN]; long long step; inline bool check() { for (int i = 1; i <= n; ++i) if (a[i] != b[i]) return 0; return 1; } int cycle[MaxN], ctot; bool vis[MaxN], flag; int father[MaxN], depth[MaxN]; void dfs_init(int now) { vis[now] = 1; for (int i = G.en[now]; i; i = G.next[i]) if (!vis[G.to[i]]) { father[G.to[i]] = now; depth[G.to[i]] = depth[now] + 1; dfs_init(G.to[i]); } } int get_lca(int u, int v) { while (u != v) { if (depth[u] > depth[v]) u = father[u]; else v = father[v]; } return u; } int get_dist(int l, int u) { return depth[u] - depth[l]; } void dfs_edge(int now) { vis[now] = 1; int deg = 0; for (int i = G.en[now]; i; i = G.next[i]) if (diff[G.to[i]]) { ++deg; if (!vis[G.to[i]]) dfs_edge(G.to[i]); } if (deg == 1) { if (edge_u) edge_v = now; else edge_u = now; } if (deg > 2) flag = 1; } void dfs_cycle(int now) { cycle[++ctot] = now; vis[now] = 1; for (int i = G.en[now]; i; i = G.next[i]) if (!vis[G.to[i]] && diff[G.to[i]]) dfs_cycle(G.to[i]); } int get_deg(int u) { int deg = 0; for (int i = G.en[u]; i; i = G.next[i]) deg += diff[G.to[i]]; return deg; } int pos[MaxN]; void solve_cycle(int in, int out) { for (int u = 1; u <= n; ++u) if (get_deg(u) == 2) diff[u] = 1; memset(vis, 0, sizeof(vis)); ; dfs_edge(in); if (flag) return; if (edge_u > edge_v) swap(edge_u, edge_v); G.add_edge(edge_u, edge_v); G.add_edge(edge_v, edge_u); memset(vis, 0, sizeof(vis)); ; dfs_cycle(in); if (!vis[out]) return; int node = 0; for (int i = 1; i <= ctot; ++i) if (cycle[i] != out) { pos[b[cycle[i]]] = ++node; } int delta = pos[a[cycle[2]]] - 1; for (int i = 2; i <= ctot; ++i) { int tmp = pos[a[cycle[i]]] - i + 1; if (tmp < 0) tmp += ctot - 1; if (tmp != delta) return; } int post = 0; for (int i = 1; i <= ctot; ++i) if (cycle[i] == out) post = i; long long now = inf, st; st = 1ll * delta * ctot - (post - 1); if (st < 0) st = -st; now = min(now, st); st = 1ll * (ctot - delta - 1) * ctot + (post - 1); if (st < 0) st = -st; now = min(now, st); step += now; for (int i = 1; i <= ctot; ++i) a[cycle[i]] = b[cycle[i]]; } void go(int& s, int* a, int* b) { while (true) { int pos = 0, deg = 0; for (int i = G.en[s]; i; i = G.next[i]) if (a[G.to[i]] != b[G.to[i]]) { ++deg; if (a[G.to[i]] == b[s]) pos = G.to[i]; } if (!pos || (deg != 1)) return; swap(a[s], a[pos]); s = pos; ++step; } } int bfs(int& s) { static int q[MaxN], dist[MaxN]; int l = 0, r = 0; memset(dist, 63, sizeof(dist)); q[++r] = s; dist[s] = 0; while (l != r) { int u = q[++l]; for (int i = G.en[u]; i; i = G.next[i]) if (dist[G.to[i]] > dist[u] + 1) { dist[G.to[i]] = dist[u] + 1; q[++r] = G.to[i]; if (diff[G.to[i]]) { s = u; return dist[u]; } } } return -1; } int main() { int s, t; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", a + i); if (a[i] == 0) s = i; } for (int i = 1; i <= n; ++i) { scanf("%d", b + i); if (b[i] == 0) t = i; } for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); G.add_edge(u, v); G.add_edge(v, u); } int ss = s, tt = t; go(s, a, b); if (check()) { printf("0 %I64d\n", step); return 0; } go(t, b, a); if ((a[t] == b[s]) && (a[s] == b[t])) { swap(a[t], a[s]); if (check()) { printf("%d %d %I64d\n", min(s, t), max(s, t), step + 1); return 0; } swap(a[t], a[s]); } int root = 0; for (int i = 1; i <= n; ++i) { diff[i] = (a[i] != b[i]); if (diff[i]) root = i; } memset(vis, 0, sizeof(vis)); ; dfs_init(root); if (a[s] == b[s]) { int l = get_lca(ss, tt); step = get_dist(l, ss) + get_dist(l, tt); step += 2 * bfs(l); solve_cycle(l, l); } else solve_cycle(s, t); if (!check()) printf("-1\n"); else printf("%d %d %I64d\n", edge_u, edge_v, step); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, a[N], b[N], s, t, deg[N]; vector<int> e1[N], f, g, Ap, Bp; int dfs1(int x, int fa) { f.push_back(x); if (x == t) return 1; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int check = dfs1(y, x); if (check) return 1; } } f.pop_back(); return 0; } int c[2]; bool vis[N]; void dfs2(int x, int fa, int k) { if (a[x] != b[x]) { g.push_back(x); vis[x] = 1; if (k - 1 == c[0] && fa != c[1]) printf("-1"), exit(0); if (k - 1 < c[0]) c[0] = k - 1, c[1] = fa; } int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) dfs2(y, x, k + 1); } return; } void dfs3(int x, int fa, int aim) { if (x != aim) Ap.push_back(a[x]), Bp.push_back(b[x]); int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa && vis[y]) dfs3(y, x, aim); } return; } int calc(vector<int> x, vector<int> y) { int res = 0, sizx = x.size(), sizy = y.size(); for (int i = 0; i < sizy; i++) if (y[i] == x[0]) res = i; if (res == 0) return -1; for (int i = 0; i < sizx; i++) if (x[i] != y[(i + res) % sizx]) return -1; return res; } int dfs4(int x, int fa, int dis, int aim) { if (x == aim) return dis; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int res = dfs4(y, x, dis + 1, aim); if (res != -1) return res; } } return -1; } long long solve(int x, int y) { int op1 = calc(Ap, Bp); long long res = dfs4(s, 0, 0, x) + 1ll * (op1 - 1) * (Ap.size() + 1) + 1 + dfs4(y, 0, 0, t); return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1; i <= n; i++) { if (a[i] == 0) s = i; if (b[i] == 0) t = i; } for (int i = 1; i <= n - 1; i++) { int x, y; scanf("%d%d", &x, &y); e1[x].push_back(y); e1[y].push_back(x); } dfs1(s, 0); int siz = f.size(); for (int i = 1; i < siz; i++) swap(a[f[i]], a[f[i - 1]]); bool check = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) check = 0; if (check) { printf("0 %d", siz - 1); return 0; } c[0] = n + 1, c[1] = 0; dfs2(t, 0, 0); int p1 = c[1]; vis[p1] = 1; g.push_back(p1); siz = g.size(); for (int i = 0; i < siz; i++) { int siz1 = e1[g[i]].size(); for (int j = 0; j < siz1; j++) { int y = e1[g[i]][j]; if (vis[y]) deg[g[i]]++; } } vector<int> h; for (int i = 0; i < siz; i++) if (deg[g[i]] == 1) h.push_back(g[i]); else if (deg[g[i]] != 2) return printf("-1"), 0; if (h.size() != 2) return printf("-1"), 0; if (h[0] > h[1]) swap(h[0], h[1]); dfs3(h[0], 0, p1); if (calc(Ap, Bp) == -1) return printf("-1"), 0; long long ans1 = solve(h[0], h[1]); int sizA = Ap.size(), sizB = Bp.size(); for (int i = 0; i < sizA; i++) if ((sizA - i - 1) > i) swap(Ap[i], Ap[sizA - i - 1]); for (int i = 0; i < sizB; i++) if ((sizB - i - 1) > i) swap(Bp[i], Bp[sizB - i - 1]); long long ans2 = solve(h[1], h[0]); printf("%d %d %lld", h[0], h[1], min(ans1, ans2)); return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, a[N], b[N], s, t, deg[N]; vector<int> e1[N], f, g, Ap, Bp; int dfs1(int x, int fa) { f.push_back(x); if (x == t) return 1; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int check = dfs1(y, x); if (check) return 1; } } f.pop_back(); return 0; } int c[2]; bool vis[N]; void dfs2(int x, int fa, int k) { if (a[x] != b[x]) { g.push_back(x); vis[x] = 1; if (k - 1 == c[0] && fa != c[1]) printf("-1"), exit(0); if (k - 1 < c[0]) c[0] = k - 1, c[1] = fa; } int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) dfs2(y, x, k + 1); } return; } void dfs3(int x, int fa, int aim) { if (x != aim) Ap.push_back(a[x]), Bp.push_back(b[x]); int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa && vis[y]) dfs3(y, x, aim); } return; } int calc(vector<int> x, vector<int> y) { int res = 0, sizx = x.size(), sizy = y.size(); for (int i = 0; i < sizy; i++) if (y[i] == x[0]) res = i; if (res == 0) return -1; for (int i = 0; i < sizx; i++) if (x[i] != y[(i + res) % sizx]) return -1; return res; } int dfs4(int x, int fa, int dis, int aim) { if (x == aim) return dis; int siz = e1[x].size(); for (int i = 0; i < siz; i++) { int y = e1[x][i]; if (y != fa) { int res = dfs4(y, x, dis + 1, aim); if (res != -1) return res; } } return -1; } long long solve(int x, int y) { int op1 = calc(Ap, Bp); long long res = dfs4(s, 0, 0, x) + 1ll * (op1 - 1) * (Ap.size() + 1) + 1 + dfs4(y, 0, 0, t); return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1; i <= n; i++) { if (a[i] == 0) s = i; if (b[i] == 0) t = i; } for (int i = 1; i <= n - 1; i++) { int x, y; scanf("%d%d", &x, &y); e1[x].push_back(y); e1[y].push_back(x); } dfs1(s, 0); int siz = f.size(); for (int i = 1; i < siz; i++) swap(a[f[i]], a[f[i - 1]]); bool check = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) check = 0; if (check) { printf("0 %d", siz - 1); return 0; } c[0] = n + 1, c[1] = 0; dfs2(t, 0, 0); int p1 = c[1]; vis[p1] = 1; g.push_back(p1); siz = g.size(); for (int i = 0; i < siz; i++) { int siz1 = e1[g[i]].size(); for (int j = 0; j < siz1; j++) { int y = e1[g[i]][j]; if (vis[y]) deg[g[i]]++; } } vector<int> h; for (int i = 0; i < siz; i++) if (deg[g[i]] == 1) h.push_back(g[i]); else if (deg[g[i]] != 2) return printf("-1"), 0; if (h.size() != 2) return printf("-1"), 0; if (h[0] > h[1]) swap(h[0], h[1]); dfs3(h[0], 0, p1); if (calc(Ap, Bp) == -1) return printf("-1"), 0; long long ans1 = solve(h[0], h[1]); int sizA = Ap.size(), sizB = Bp.size(); for (int i = 0; i < sizA; i++) if ((sizA - i - 1) > i) swap(Ap[i], Ap[sizA - i - 1]); for (int i = 0; i < sizB; i++) if ((sizB - i - 1) > i) swap(Bp[i], Bp[sizB - i - 1]); long long ans2 = solve(h[1], h[0]); printf("%d %d %lld", h[0], h[1], min(ans1, ans2)); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int Maxn = 200005; int n, s, t, p, cnt, a[Maxn], b[Maxn], deg[Maxn], head[Maxn]; vector<int> A, B, Ve1, Ve, spec; pair<int, int> mini = make_pair(0x3f3f3f3f, 0); bool vis[Maxn]; struct edg { int nxt, to; } edge[2 * Maxn]; void add(int x, int y) { edge[++cnt] = (edg){head[x], y}; head[x] = cnt; } bool dfs1(int u, int fa) { Ve1.push_back(u); if (u == t) return true; for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa && dfs1(to, u)) return true; } Ve1.pop_back(); return false; } void dfs2(int u, int fa, int dep) { if (a[u] != b[u]) { Ve.push_back(u); if (dep == mini.first && fa != mini.second) { puts("-1"); exit(0); } if (dep < mini.first) mini = make_pair(dep, fa); } for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa) dfs2(to, u, dep + 1); } } void dfs3(int u, int fa) { if (u != p) A.push_back(a[u]), B.push_back(b[u]); for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa && vis[to]) dfs3(to, u); } } int dfs4(int u, int fa, int dep, int goal) { if (u == goal) return dep; for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa) { int result = dfs4(to, u, dep + 1, goal); if (result) return result; } } return 0; } int get_shift(void) { int pos = 0; for (int i = 0; i < (int)B.size(); i++) if (A[0] == B[i]) pos = i; if (!pos) return 0; for (int i = 0; i < (int)B.size(); i++) if (A[i] != B[(i + pos) % (int)B.size()]) return 0; return pos; } int get_dis(int x, int y) { return dfs4(x, 0, 0, y); } long long work(int x, int y) { int c = get_shift(); return (c - 1LL) * (A.size() + 1) + 1 + get_dis(s, x) + get_dis(y, t); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), s = (a[i] == 0 ? i : s); for (int i = 1; i <= n; i++) scanf("%d", &b[i]), t = (b[i] == 0 ? i : t); for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); add(x, y), add(y, x); } dfs1(s, 0); for (int i = 1; i < (int)Ve1.size(); i++) swap(a[Ve1[i]], a[Ve1[i - 1]]); bool flag = true; for (int i = 1; i <= n; i++) if (a[i] != b[i]) flag = false; if (flag) { printf("%d %d\n", 0, (int)Ve1.size() - 1); return 0; } dfs2(t, 0, 0); p = mini.second, Ve.push_back(p); for (auto u : Ve) vis[u] = true; for (auto u : Ve) for (int i = head[u]; i; i = edge[i].nxt) deg[edge[i].to]++; for (auto u : Ve) if (deg[u] == 1) spec.push_back(u); else if (deg[u] != 2) { puts("-1"); return 0; } if (spec.size() != 2) { puts("-1"); return 0; } int u = spec[0], v = spec[1]; if (u > v) swap(u, v); dfs3(u, 0); if (!get_shift()) { puts("-1"); return 0; } printf("%d %d ", u, v); long long result = work(u, v); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); printf("%lld", min(result, work(v, u))); return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int Maxn = 200005; int n, s, t, p, cnt, a[Maxn], b[Maxn], deg[Maxn], head[Maxn]; vector<int> A, B, Ve1, Ve, spec; pair<int, int> mini = make_pair(0x3f3f3f3f, 0); bool vis[Maxn]; struct edg { int nxt, to; } edge[2 * Maxn]; void add(int x, int y) { edge[++cnt] = (edg){head[x], y}; head[x] = cnt; } bool dfs1(int u, int fa) { Ve1.push_back(u); if (u == t) return true; for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa && dfs1(to, u)) return true; } Ve1.pop_back(); return false; } void dfs2(int u, int fa, int dep) { if (a[u] != b[u]) { Ve.push_back(u); if (dep == mini.first && fa != mini.second) { puts("-1"); exit(0); } if (dep < mini.first) mini = make_pair(dep, fa); } for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa) dfs2(to, u, dep + 1); } } void dfs3(int u, int fa) { if (u != p) A.push_back(a[u]), B.push_back(b[u]); for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa && vis[to]) dfs3(to, u); } } int dfs4(int u, int fa, int dep, int goal) { if (u == goal) return dep; for (int i = head[u]; i; i = edge[i].nxt) { int to = edge[i].to; if (to != fa) { int result = dfs4(to, u, dep + 1, goal); if (result) return result; } } return 0; } int get_shift(void) { int pos = 0; for (int i = 0; i < (int)B.size(); i++) if (A[0] == B[i]) pos = i; if (!pos) return 0; for (int i = 0; i < (int)B.size(); i++) if (A[i] != B[(i + pos) % (int)B.size()]) return 0; return pos; } int get_dis(int x, int y) { return dfs4(x, 0, 0, y); } long long work(int x, int y) { int c = get_shift(); return (c - 1LL) * (A.size() + 1) + 1 + get_dis(s, x) + get_dis(y, t); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), s = (a[i] == 0 ? i : s); for (int i = 1; i <= n; i++) scanf("%d", &b[i]), t = (b[i] == 0 ? i : t); for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); add(x, y), add(y, x); } dfs1(s, 0); for (int i = 1; i < (int)Ve1.size(); i++) swap(a[Ve1[i]], a[Ve1[i - 1]]); bool flag = true; for (int i = 1; i <= n; i++) if (a[i] != b[i]) flag = false; if (flag) { printf("%d %d\n", 0, (int)Ve1.size() - 1); return 0; } dfs2(t, 0, 0); p = mini.second, Ve.push_back(p); for (auto u : Ve) vis[u] = true; for (auto u : Ve) for (int i = head[u]; i; i = edge[i].nxt) deg[edge[i].to]++; for (auto u : Ve) if (deg[u] == 1) spec.push_back(u); else if (deg[u] != 2) { puts("-1"); return 0; } if (spec.size() != 2) { puts("-1"); return 0; } int u = spec[0], v = spec[1]; if (u > v) swap(u, v); dfs3(u, 0); if (!get_shift()) { puts("-1"); return 0; } printf("%d %d ", u, v); long long result = work(u, v); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); printf("%lld", min(result, work(v, u))); return 0; } ```
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, c = getchar(), f = 0; for (; c > '9' || c < '0'; f = c == '-', c = getchar()) ; for (; c >= '0' && c <= '9'; x = (x << 1) + (x << 3) + c - '0', c = getchar()) ; return f ? -x : x; } inline void write(int x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + 48); } const int N = 200000 + 10; struct edge { int to, nxt; } e[N * 2]; int n, ecnt, head[N]; void addedge(int u, int v) { e[++ecnt] = (edge){v, head[u]}; head[u] = ecnt; e[++ecnt] = (edge){u, head[v]}; head[v] = ecnt; } void init(int *a) { for (int i = (int)1, _y = n; i <= _y; i++) { a[i] = read(); if (!a[i]) a[0] = i; } } int dep[N], fa[N]; void dfs(int u) { for (int i = head[u], v; i; i = e[i].nxt) if ((v = e[i].to) != fa[u]) { dep[v] = dep[u] + 1; fa[v] = u; dfs(v); } } int a[N], b[N], lca; bool vis[N]; pair<int, int> lx[N], ly[N]; void find(int &x) { for (int i = (int)1, _y = n; i <= _y; i++) if (a[i] != b[i] && !vis[i] && (!x || dep[i] > dep[x])) x = i; if (!x) { x = lca; return; } int i = x; for (vis[i] = 1; a[fa[i]] != b[fa[i]]; vis[i] = 1) i = fa[i]; if (lca && lca != fa[i]) puts("-1"), exit(0); lca = fa[i]; } int getlca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (; dep[x] != dep[y]; x = fa[x]) ; for (; x != y; x = fa[x], y = fa[y]) ; return x; } int main() { n = read(); init(a); init(b); for (int i = (int)1, _y = n - 1; i <= _y; i++) addedge(read(), read()); dfs(*b); for (int i = *a; i != *b; i = fa[i]) swap(a[i], a[fa[i]]); bool flag = 1; for (int i = (int)1, _y = n; i <= _y; i++) if (a[i] != b[i]) { flag = 0; break; } if (flag) return printf("0 %d\n", dep[*a]), 0; int x = 0, y = 0; find(x); find(y); for (int i = (int)1, _y = n; i <= _y; i++) if (a[i] != b[i] && !vis[i]) puts("-1"), exit(0); if (x > y) swap(x, y); int lenx = 0, leny = 0; for (int i = x; i != lca; i = fa[i]) lx[++lenx] = make_pair(a[i], b[i]); for (int i = y; i != lca; i = fa[i]) ly[++leny] = make_pair(a[i], b[i]); for (; leny;) lx[++lenx] = ly[leny--]; int loop = lenx + 1, pos = 0; for (int i = (int)1, _y = lenx; i <= _y; i++) if (lx[i].second == lx[1].first) { pos = i; break; } if (!pos) puts("-1"), exit(0); for (int i = (int)1, _y = lenx; i <= _y; i++) if (lx[i].first != lx[(pos + i - 2) % lenx + 1].second) puts("-1"), exit(0); int qs = min(pos - 1, lenx - pos + 1); printf("%d %d ", x, y); int LX = getlca(*a, x), RX = getlca(*a, y); if (dep[LX] < dep[lca] || (LX == lca && RX == lca)) printf("%lld\n", dep[*a] + dep[lca] - 2 * dep[LX] + (long long)qs * loop + dep[lca]); else { long long ans1, ans2; if (LX == lca) ans1 = dep[*a] + (long long)(pos - 1) * loop, ans2 = dep[*a] + (long long)(loop - pos) * loop - (dep[RX] - dep[lca]) * 2; else ans1 = dep[*a] + (long long)(loop - pos) * loop, ans2 = dep[*a] + (long long)(pos - 1) * loop - (dep[LX] - dep[lca]) * 2; printf("%lld\n", min(ans1, ans2)); } }
### Prompt Develop a solution in CPP to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, c = getchar(), f = 0; for (; c > '9' || c < '0'; f = c == '-', c = getchar()) ; for (; c >= '0' && c <= '9'; x = (x << 1) + (x << 3) + c - '0', c = getchar()) ; return f ? -x : x; } inline void write(int x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + 48); } const int N = 200000 + 10; struct edge { int to, nxt; } e[N * 2]; int n, ecnt, head[N]; void addedge(int u, int v) { e[++ecnt] = (edge){v, head[u]}; head[u] = ecnt; e[++ecnt] = (edge){u, head[v]}; head[v] = ecnt; } void init(int *a) { for (int i = (int)1, _y = n; i <= _y; i++) { a[i] = read(); if (!a[i]) a[0] = i; } } int dep[N], fa[N]; void dfs(int u) { for (int i = head[u], v; i; i = e[i].nxt) if ((v = e[i].to) != fa[u]) { dep[v] = dep[u] + 1; fa[v] = u; dfs(v); } } int a[N], b[N], lca; bool vis[N]; pair<int, int> lx[N], ly[N]; void find(int &x) { for (int i = (int)1, _y = n; i <= _y; i++) if (a[i] != b[i] && !vis[i] && (!x || dep[i] > dep[x])) x = i; if (!x) { x = lca; return; } int i = x; for (vis[i] = 1; a[fa[i]] != b[fa[i]]; vis[i] = 1) i = fa[i]; if (lca && lca != fa[i]) puts("-1"), exit(0); lca = fa[i]; } int getlca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (; dep[x] != dep[y]; x = fa[x]) ; for (; x != y; x = fa[x], y = fa[y]) ; return x; } int main() { n = read(); init(a); init(b); for (int i = (int)1, _y = n - 1; i <= _y; i++) addedge(read(), read()); dfs(*b); for (int i = *a; i != *b; i = fa[i]) swap(a[i], a[fa[i]]); bool flag = 1; for (int i = (int)1, _y = n; i <= _y; i++) if (a[i] != b[i]) { flag = 0; break; } if (flag) return printf("0 %d\n", dep[*a]), 0; int x = 0, y = 0; find(x); find(y); for (int i = (int)1, _y = n; i <= _y; i++) if (a[i] != b[i] && !vis[i]) puts("-1"), exit(0); if (x > y) swap(x, y); int lenx = 0, leny = 0; for (int i = x; i != lca; i = fa[i]) lx[++lenx] = make_pair(a[i], b[i]); for (int i = y; i != lca; i = fa[i]) ly[++leny] = make_pair(a[i], b[i]); for (; leny;) lx[++lenx] = ly[leny--]; int loop = lenx + 1, pos = 0; for (int i = (int)1, _y = lenx; i <= _y; i++) if (lx[i].second == lx[1].first) { pos = i; break; } if (!pos) puts("-1"), exit(0); for (int i = (int)1, _y = lenx; i <= _y; i++) if (lx[i].first != lx[(pos + i - 2) % lenx + 1].second) puts("-1"), exit(0); int qs = min(pos - 1, lenx - pos + 1); printf("%d %d ", x, y); int LX = getlca(*a, x), RX = getlca(*a, y); if (dep[LX] < dep[lca] || (LX == lca && RX == lca)) printf("%lld\n", dep[*a] + dep[lca] - 2 * dep[LX] + (long long)qs * loop + dep[lca]); else { long long ans1, ans2; if (LX == lca) ans1 = dep[*a] + (long long)(pos - 1) * loop, ans2 = dep[*a] + (long long)(loop - pos) * loop - (dep[RX] - dep[lca]) * 2; else ans1 = dep[*a] + (long long)(loop - pos) * loop, ans2 = dep[*a] + (long long)(pos - 1) * loop - (dep[LX] - dep[lca]) * 2; printf("%lld\n", min(ans1, ans2)); } } ```
#include <bits/stdc++.h> using namespace std; const int N = 200005; struct edge { int to, next; } e[N * 2]; int head[N], tot, n; int a[N], b[N], aa[N]; int dfn[N], ed[N], dep[N]; int fa[N][19], A[N], B[N]; int pos1, pos2, cnt; void add(int x, int y) { e[++tot] = (edge){y, head[x]}; head[x] = tot; } bool dfs(int x, int fa, int ed) { if (x == ed) return 1; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa) if (dfs(e[i].to, x, ed)) { ++cnt; swap(aa[e[i].to], aa[x]); return 1; } return 0; } void walk(int x, int y) { dfs(y, 0, x); } bool OJBK() { for (int i = (int)(1); i <= (int)(n); i++) if (aa[i] != b[i]) return 0; return 1; } void dfs(int x) { dfn[x] = ++*dfn; for (int i = (int)(1); i <= (int)(17); i++) fa[x][i] = fa[fa[x][i - 1]][i - 1]; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa[x][0]) { fa[e[i].to][0] = x; dep[e[i].to] = dep[x] + 1; dfs(e[i].to); } ed[x] = *dfn; } bool isfa(int x, int y) { return dfn[x] <= dfn[y] && ed[y] <= ed[x]; } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); int tmp = dep[x] - dep[y]; for (int i = (int)(0); i <= (int)(17); i++) if (tmp & (1 << i)) x = fa[x][i]; for (int i = (int)(17); i >= (int)(0); i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return x == y ? x : fa[x][0]; } pair<int, int> merge(pair<int, int> x, int y) { if (!x.first) return pair<int, int>(y, y); int c[3]; c[0] = x.first; c[1] = x.second; c[2] = y; int L = LCA(c[0], c[1]); if (isfa(L, c[2]) && (isfa(c[2], c[0]) || isfa(c[2], c[1]))) return pair<int, int>(c[0], c[1]); L = LCA(c[0], c[2]); if (isfa(L, c[1]) && (isfa(c[1], c[0]) || isfa(c[1], c[2]))) return pair<int, int>(c[0], c[2]); L = LCA(c[1], c[2]); if (isfa(L, c[0]) && (isfa(c[0], c[1]) || isfa(c[0], c[2]))) return pair<int, int>(c[1], c[2]); puts("-1"); exit(0); } long long solve(int x, int y) { int L = LCA(x, y); int l = 1, r = dep[x] + dep[y] - 2 * dep[L], len = r, at = l; for (; x != L; x = fa[x][0], ++l) A[l] = aa[x], B[l] = b[x]; for (; y != L; y = fa[y][0], --r) A[r] = aa[y], B[r] = b[y]; for (; A[1] != B[at]; ++at) ; for (int i = (int)(1); i <= (int)(len); i++) if (A[i] != B[(i + at - 2) % len + 1]) return 1ll << 55; return 1ll * min(at - 1, len + 1 - at) * (len + 1); } int main() { scanf("%d", &n); for (int i = (int)(1); i <= (int)(n); i++) scanf("%d", &a[i]); for (int i = (int)(1); i <= (int)(n); i++) scanf("%d", &b[i]); for (int i = (int)(1); i <= (int)(n); i++) if (!a[i]) pos1 = i; for (int i = (int)(1); i <= (int)(n); i++) if (!b[i]) pos2 = i; for (int i = (int)(1); i <= (int)(n - 1); i++) { int x, y; scanf("%d%d", &x, &y); add(x, y); add(y, x); } dfs(pos2); memcpy(aa, a, sizeof(aa)); walk(pos1, pos2); if (OJBK()) { printf("0 %d\n", cnt); return 0; } pair<int, int> tmp(0, 0); for (int i = (int)(1); i <= (int)(n); i++) if (aa[i] != b[i]) tmp = merge(tmp, i); if (dep[tmp.first] > dep[tmp.second]) swap(tmp.first, tmp.second); if (isfa(tmp.first, tmp.second)) tmp.first = fa[tmp.first][0]; long long ans = 1ll << 60; cnt = 0; memcpy(aa, a, sizeof(aa)); walk(pos1, tmp.first); swap(aa[tmp.first], aa[tmp.second]), ++cnt; walk(tmp.second, pos2); ans = min(ans, cnt + solve(tmp.first, tmp.second)); cnt = 0; memcpy(aa, a, sizeof(aa)); walk(pos1, tmp.second); swap(aa[tmp.second], aa[tmp.first]), ++cnt; walk(tmp.first, pos2); ans = min(ans, cnt + solve(tmp.first, tmp.second)); if (ans > 1ll << 50) puts("-1"); else { if (tmp.first > tmp.second) swap(tmp.first, tmp.second); printf("%d %d %lld\n", tmp.first, tmp.second, ans); } }
### Prompt Please formulate a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200005; struct edge { int to, next; } e[N * 2]; int head[N], tot, n; int a[N], b[N], aa[N]; int dfn[N], ed[N], dep[N]; int fa[N][19], A[N], B[N]; int pos1, pos2, cnt; void add(int x, int y) { e[++tot] = (edge){y, head[x]}; head[x] = tot; } bool dfs(int x, int fa, int ed) { if (x == ed) return 1; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa) if (dfs(e[i].to, x, ed)) { ++cnt; swap(aa[e[i].to], aa[x]); return 1; } return 0; } void walk(int x, int y) { dfs(y, 0, x); } bool OJBK() { for (int i = (int)(1); i <= (int)(n); i++) if (aa[i] != b[i]) return 0; return 1; } void dfs(int x) { dfn[x] = ++*dfn; for (int i = (int)(1); i <= (int)(17); i++) fa[x][i] = fa[fa[x][i - 1]][i - 1]; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa[x][0]) { fa[e[i].to][0] = x; dep[e[i].to] = dep[x] + 1; dfs(e[i].to); } ed[x] = *dfn; } bool isfa(int x, int y) { return dfn[x] <= dfn[y] && ed[y] <= ed[x]; } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); int tmp = dep[x] - dep[y]; for (int i = (int)(0); i <= (int)(17); i++) if (tmp & (1 << i)) x = fa[x][i]; for (int i = (int)(17); i >= (int)(0); i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return x == y ? x : fa[x][0]; } pair<int, int> merge(pair<int, int> x, int y) { if (!x.first) return pair<int, int>(y, y); int c[3]; c[0] = x.first; c[1] = x.second; c[2] = y; int L = LCA(c[0], c[1]); if (isfa(L, c[2]) && (isfa(c[2], c[0]) || isfa(c[2], c[1]))) return pair<int, int>(c[0], c[1]); L = LCA(c[0], c[2]); if (isfa(L, c[1]) && (isfa(c[1], c[0]) || isfa(c[1], c[2]))) return pair<int, int>(c[0], c[2]); L = LCA(c[1], c[2]); if (isfa(L, c[0]) && (isfa(c[0], c[1]) || isfa(c[0], c[2]))) return pair<int, int>(c[1], c[2]); puts("-1"); exit(0); } long long solve(int x, int y) { int L = LCA(x, y); int l = 1, r = dep[x] + dep[y] - 2 * dep[L], len = r, at = l; for (; x != L; x = fa[x][0], ++l) A[l] = aa[x], B[l] = b[x]; for (; y != L; y = fa[y][0], --r) A[r] = aa[y], B[r] = b[y]; for (; A[1] != B[at]; ++at) ; for (int i = (int)(1); i <= (int)(len); i++) if (A[i] != B[(i + at - 2) % len + 1]) return 1ll << 55; return 1ll * min(at - 1, len + 1 - at) * (len + 1); } int main() { scanf("%d", &n); for (int i = (int)(1); i <= (int)(n); i++) scanf("%d", &a[i]); for (int i = (int)(1); i <= (int)(n); i++) scanf("%d", &b[i]); for (int i = (int)(1); i <= (int)(n); i++) if (!a[i]) pos1 = i; for (int i = (int)(1); i <= (int)(n); i++) if (!b[i]) pos2 = i; for (int i = (int)(1); i <= (int)(n - 1); i++) { int x, y; scanf("%d%d", &x, &y); add(x, y); add(y, x); } dfs(pos2); memcpy(aa, a, sizeof(aa)); walk(pos1, pos2); if (OJBK()) { printf("0 %d\n", cnt); return 0; } pair<int, int> tmp(0, 0); for (int i = (int)(1); i <= (int)(n); i++) if (aa[i] != b[i]) tmp = merge(tmp, i); if (dep[tmp.first] > dep[tmp.second]) swap(tmp.first, tmp.second); if (isfa(tmp.first, tmp.second)) tmp.first = fa[tmp.first][0]; long long ans = 1ll << 60; cnt = 0; memcpy(aa, a, sizeof(aa)); walk(pos1, tmp.first); swap(aa[tmp.first], aa[tmp.second]), ++cnt; walk(tmp.second, pos2); ans = min(ans, cnt + solve(tmp.first, tmp.second)); cnt = 0; memcpy(aa, a, sizeof(aa)); walk(pos1, tmp.second); swap(aa[tmp.second], aa[tmp.first]), ++cnt; walk(tmp.first, pos2); ans = min(ans, cnt + solve(tmp.first, tmp.second)); if (ans > 1ll << 50) puts("-1"); else { if (tmp.first > tmp.second) swap(tmp.first, tmp.second); printf("%d %d %lld\n", tmp.first, tmp.second, ans); } } ```
#include <bits/stdc++.h> const int MN = 200005; int N, su, tu, A[MN], B[MN]; std::vector<int> G[MN]; int stk[MN], top; int faz[MN], dep[MN], sv[MN]; void DFS0(int u, int fz) { dep[u] = dep[faz[u] = fz] + 1; for (auto v : G[u]) if (v != fz) DFS0(v, u); } int DFSD(int u, int fz, int d, int t, int x) { if (u != x) stk[++top] = u; if (u == t) return d; for (auto v : G[u]) if (v != fz) { int ret = DFSD(v, u, d + 1, t, x); if (ret != -1) return ret; } if (u != x) --top; return -1; } int Dist(int u, int v, int x = 0) { return top = 0, DFSD(u, 0, 0, v, x); } int Calc(int u, int v) { return Dist(su, u) + Dist(v, tu) + 1; } int main() { scanf("%d", &N); for (int i = 1; i <= N; ++i) scanf("%d", &A[i]); for (int i = 1; i <= N; ++i) scanf("%d", &B[i]); for (int i = 1; i <= N; ++i) { if (A[i] == 0) su = i; if (B[i] == 0) tu = i; } for (int i = 1, x, y; i < N; ++i) { scanf("%d%d", &x, &y); G[x].push_back(y); G[y].push_back(x); } DFS0(tu, 0); for (int x = su; x != tu; x = faz[x]) A[x] = A[faz[x]]; A[tu] = 0; int cnt = 0, tp = 0, p = 0; static int seq[MN]; for (int i = 1; i <= N; ++i) if (A[i] != B[i]) { ++cnt, sv[faz[i]] = 1; if (!p || dep[i] <= dep[p]) p = faz[i]; } if (!cnt) return printf("0 %d\n", dep[su] - 1), 0; for (int i = 1; i <= N; ++i) if (A[i] != B[i] && !sv[i]) seq[++tp] = i; if (tp > 2) return puts("-1"), 0; if (tp == 1) seq[2] = p; if (Dist(seq[1], seq[2], p) != cnt) return puts("-1"), 0; static int iB[MN], shift; for (int i = 1; i <= top; ++i) iB[B[stk[i]]] = i; if (!iB[A[stk[1]]]) return puts("-1"), 0; else shift = iB[A[stk[1]]] - 1; for (int i = 2; i <= top; ++i) if (!iB[A[stk[i]]] || (iB[A[stk[i]]] - i + cnt) % cnt != shift) return puts("-1"), 0; int len = cnt + 1; long long cycuv = Calc(seq[1], seq[2]) + (long long)(shift - 1) * len; long long cycvu = Calc(seq[2], seq[1]) + (long long)(cnt - shift - 1) * len; if (seq[1] > seq[2]) std::swap(seq[1], seq[2]); printf("%d %d %lld\n", seq[1], seq[2], std::min(cycuv, cycvu)); return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> const int MN = 200005; int N, su, tu, A[MN], B[MN]; std::vector<int> G[MN]; int stk[MN], top; int faz[MN], dep[MN], sv[MN]; void DFS0(int u, int fz) { dep[u] = dep[faz[u] = fz] + 1; for (auto v : G[u]) if (v != fz) DFS0(v, u); } int DFSD(int u, int fz, int d, int t, int x) { if (u != x) stk[++top] = u; if (u == t) return d; for (auto v : G[u]) if (v != fz) { int ret = DFSD(v, u, d + 1, t, x); if (ret != -1) return ret; } if (u != x) --top; return -1; } int Dist(int u, int v, int x = 0) { return top = 0, DFSD(u, 0, 0, v, x); } int Calc(int u, int v) { return Dist(su, u) + Dist(v, tu) + 1; } int main() { scanf("%d", &N); for (int i = 1; i <= N; ++i) scanf("%d", &A[i]); for (int i = 1; i <= N; ++i) scanf("%d", &B[i]); for (int i = 1; i <= N; ++i) { if (A[i] == 0) su = i; if (B[i] == 0) tu = i; } for (int i = 1, x, y; i < N; ++i) { scanf("%d%d", &x, &y); G[x].push_back(y); G[y].push_back(x); } DFS0(tu, 0); for (int x = su; x != tu; x = faz[x]) A[x] = A[faz[x]]; A[tu] = 0; int cnt = 0, tp = 0, p = 0; static int seq[MN]; for (int i = 1; i <= N; ++i) if (A[i] != B[i]) { ++cnt, sv[faz[i]] = 1; if (!p || dep[i] <= dep[p]) p = faz[i]; } if (!cnt) return printf("0 %d\n", dep[su] - 1), 0; for (int i = 1; i <= N; ++i) if (A[i] != B[i] && !sv[i]) seq[++tp] = i; if (tp > 2) return puts("-1"), 0; if (tp == 1) seq[2] = p; if (Dist(seq[1], seq[2], p) != cnt) return puts("-1"), 0; static int iB[MN], shift; for (int i = 1; i <= top; ++i) iB[B[stk[i]]] = i; if (!iB[A[stk[1]]]) return puts("-1"), 0; else shift = iB[A[stk[1]]] - 1; for (int i = 2; i <= top; ++i) if (!iB[A[stk[i]]] || (iB[A[stk[i]]] - i + cnt) % cnt != shift) return puts("-1"), 0; int len = cnt + 1; long long cycuv = Calc(seq[1], seq[2]) + (long long)(shift - 1) * len; long long cycvu = Calc(seq[2], seq[1]) + (long long)(cnt - shift - 1) * len; if (seq[1] > seq[2]) std::swap(seq[1], seq[2]); printf("%d %d %lld\n", seq[1], seq[2], std::min(cycuv, cycvu)); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> sosedi[maxn]; int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n; void dfs(int v, int predok) { parent[v] = predok; shagi[v] = shagi[predok] + 1; for (auto p : sosedi[v]) if (p != predok) dfs(p, v); } vector<int> circles; int rt, lp, lq; bool find_circle() { circles.clear(); static bool visit_vertex[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && shagi[i] > shagi[p]) p = i; if (!p) return 1; for (int u = p; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[q]) q = i; if (q) { reverse(circles.begin(), circles.end()); for (int u = q; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; } else q = parent[circles.back()]; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i]) return 0; int u, v; for (u = p, v = q; u != v; u = parent[u]) if (shagi[u] < shagi[v]) swap(u, v); rt = u; if (circles.size() != shagi[p] + shagi[q] - 2 * shagi[rt]) return 0; lp = p, lq = q; return 1; } int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> start[i]; } for (int i = 1; i <= n; i++) { cin >> finish[i]; } for (int i = 1, u, v; i < n; i++) { cin >> u >> v; sosedi[u].push_back(v), sosedi[v].push_back(u); } int pa = find(start + 1, start + n + 1, 0) - start, pb = find(finish + 1, finish + n + 1, 0) - finish; shagi[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = parent[u]) swap(start[u], start[parent[u]]); long long ans = shagi[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!circles.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = circles.size(); for (int i = 0; i < len; i++) if (finish[circles[i]] == start[circles[0]]) gap = i; for (int i = 1; i < len; i++) if (finish[circles[(i + gap) % len]] != start[circles[i]]) { printf("-1\n"); return 0; } static bool visit_vertex[maxn]; for (int i = pa; i; i = parent[i]) visit_vertex[i] = 1; if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) { int po = circles.size(); for (int i = 0; i < circles.size(); i++) if (!visit_vertex[circles[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !visit_vertex[rt]; rt = parent[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> sosedi[maxn]; int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n; void dfs(int v, int predok) { parent[v] = predok; shagi[v] = shagi[predok] + 1; for (auto p : sosedi[v]) if (p != predok) dfs(p, v); } vector<int> circles; int rt, lp, lq; bool find_circle() { circles.clear(); static bool visit_vertex[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && shagi[i] > shagi[p]) p = i; if (!p) return 1; for (int u = p; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[q]) q = i; if (q) { reverse(circles.begin(), circles.end()); for (int u = q; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; } else q = parent[circles.back()]; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i]) return 0; int u, v; for (u = p, v = q; u != v; u = parent[u]) if (shagi[u] < shagi[v]) swap(u, v); rt = u; if (circles.size() != shagi[p] + shagi[q] - 2 * shagi[rt]) return 0; lp = p, lq = q; return 1; } int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> start[i]; } for (int i = 1; i <= n; i++) { cin >> finish[i]; } for (int i = 1, u, v; i < n; i++) { cin >> u >> v; sosedi[u].push_back(v), sosedi[v].push_back(u); } int pa = find(start + 1, start + n + 1, 0) - start, pb = find(finish + 1, finish + n + 1, 0) - finish; shagi[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = parent[u]) swap(start[u], start[parent[u]]); long long ans = shagi[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!circles.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = circles.size(); for (int i = 0; i < len; i++) if (finish[circles[i]] == start[circles[0]]) gap = i; for (int i = 1; i < len; i++) if (finish[circles[(i + gap) % len]] != start[circles[i]]) { printf("-1\n"); return 0; } static bool visit_vertex[maxn]; for (int i = pa; i; i = parent[i]) visit_vertex[i] = 1; if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) { int po = circles.size(); for (int i = 0; i < circles.size(); i++) if (!visit_vertex[circles[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !visit_vertex[rt]; rt = parent[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; inline int read() { int n = 0; char c; for (c = getchar(); c < '0' || c > '9'; c = getchar()) ; for (; c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - 48; return n; } const int maxn = 2e5 + 5; int t, n, i, j, a[maxn], b[maxn], S, T, f[maxn], d[maxn]; int x, y, lc, len, B; bool bz[maxn], bk[maxn]; vector<int> g[maxn], c; long long ans; void dfs(int x, int fa) { f[x] = fa, d[x] = fa != -1 ? d[fa] + 1 : 0; for (int i = 0; i < g[x].size(); i++) { int y = g[x][i]; if (y != fa) dfs(y, x); } } int main() { n = read(); for (i = 0; i <= n - 1; i++) a[i] = read(), S = a[i] ? S : i; for (i = 0; i <= n - 1; i++) b[i] = read(), T = b[i] ? T : i; for (i = 1; i <= n - 1; i++) { int x = read() - 1, y = read() - 1; g[x].push_back(y), g[y].push_back(x); } dfs(T, -1), ans = d[S]; for (i = S; i != T; i = f[i]) bk[i] = 1, swap(a[i], a[f[i]]); x = y = -1, bk[T] = 1; for (i = 0; i <= n - 1; i++) if (a[i] != b[i]) x = x == -1 || d[i] > d[x] ? i : x; if (x < 0) return printf("0 %d\n", ans), 0; for (i = x; a[i] != b[i]; i = f[i]) c.push_back(i), bz[i] = 1; for (i = 0; i <= n - 1; i++) if (!bz[i] && a[i] != b[i]) y = y == -1 || d[i] > d[y] ? i : y; if (y < 0) y = f[c.back()]; else { reverse(c.begin(), c.end()); for (i = y; a[i] != b[i]; i = f[i]) c.push_back(i), bz[i] = 1; for (i = 0; i <= n - 1; i++) if (!bz[i] && a[i] != b[i]) return puts("-1"), 0; } for (i = x, j = y; i != j;) if (d[i] > d[j]) i = f[i]; else j = f[j]; lc = i, len = c.size(); if (a[lc] != b[lc] || (d[x] + d[y] - d[lc] * 2 != len)) return puts("-1"), 0; for (i = 0; i <= len - 1; i++) if (a[c[i]] == b[c[0]]) break; B = i; for (i = 0; i <= len - 1; i++) if (a[c[(i + B) % len]] != b[c[i]]) return puts("-1"), 0; if (bk[c[0]] || bk[c[len - 1]]) { if (bk[c[len - 1]]) reverse(c.begin(), c.end()), B = len - B; for (i = 0; i <= len - 1; i++) if (!bk[c[i]]) break; long long s1 = (long long)B * (len + 1) - i * 2, s2 = (long long)(len - B) * (len + 1); ans += (s1 < s2 ? s1 : s2); } else ans += (long long)(B < len - B ? B : len - B) * (len + 1); for (; !bk[lc]; lc = f[lc]) ans += 2; if (x > y) swap(x, y); printf("%d %d %lld\n", x + 1, y + 1, ans); }
### Prompt Construct a CPP code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int n = 0; char c; for (c = getchar(); c < '0' || c > '9'; c = getchar()) ; for (; c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - 48; return n; } const int maxn = 2e5 + 5; int t, n, i, j, a[maxn], b[maxn], S, T, f[maxn], d[maxn]; int x, y, lc, len, B; bool bz[maxn], bk[maxn]; vector<int> g[maxn], c; long long ans; void dfs(int x, int fa) { f[x] = fa, d[x] = fa != -1 ? d[fa] + 1 : 0; for (int i = 0; i < g[x].size(); i++) { int y = g[x][i]; if (y != fa) dfs(y, x); } } int main() { n = read(); for (i = 0; i <= n - 1; i++) a[i] = read(), S = a[i] ? S : i; for (i = 0; i <= n - 1; i++) b[i] = read(), T = b[i] ? T : i; for (i = 1; i <= n - 1; i++) { int x = read() - 1, y = read() - 1; g[x].push_back(y), g[y].push_back(x); } dfs(T, -1), ans = d[S]; for (i = S; i != T; i = f[i]) bk[i] = 1, swap(a[i], a[f[i]]); x = y = -1, bk[T] = 1; for (i = 0; i <= n - 1; i++) if (a[i] != b[i]) x = x == -1 || d[i] > d[x] ? i : x; if (x < 0) return printf("0 %d\n", ans), 0; for (i = x; a[i] != b[i]; i = f[i]) c.push_back(i), bz[i] = 1; for (i = 0; i <= n - 1; i++) if (!bz[i] && a[i] != b[i]) y = y == -1 || d[i] > d[y] ? i : y; if (y < 0) y = f[c.back()]; else { reverse(c.begin(), c.end()); for (i = y; a[i] != b[i]; i = f[i]) c.push_back(i), bz[i] = 1; for (i = 0; i <= n - 1; i++) if (!bz[i] && a[i] != b[i]) return puts("-1"), 0; } for (i = x, j = y; i != j;) if (d[i] > d[j]) i = f[i]; else j = f[j]; lc = i, len = c.size(); if (a[lc] != b[lc] || (d[x] + d[y] - d[lc] * 2 != len)) return puts("-1"), 0; for (i = 0; i <= len - 1; i++) if (a[c[i]] == b[c[0]]) break; B = i; for (i = 0; i <= len - 1; i++) if (a[c[(i + B) % len]] != b[c[i]]) return puts("-1"), 0; if (bk[c[0]] || bk[c[len - 1]]) { if (bk[c[len - 1]]) reverse(c.begin(), c.end()), B = len - B; for (i = 0; i <= len - 1; i++) if (!bk[c[i]]) break; long long s1 = (long long)B * (len + 1) - i * 2, s2 = (long long)(len - B) * (len + 1); ans += (s1 < s2 ? s1 : s2); } else ans += (long long)(B < len - B ? B : len - B) * (len + 1); for (; !bk[lc]; lc = f[lc]) ans += 2; if (x > y) swap(x, y); printf("%d %d %lld\n", x + 1, y + 1, ans); } ```
#include <bits/stdc++.h> using namespace std; bool bo[200010]; int la[200010], a[200010], b[200010], pa[200010], pb[200010], x, y, hd[200010], cnt, n, t[2][200010], tn[2], sa, sb, c[200010], cn, d[200010], q[200010], l, r, C[200010], Cn; struct node { int to, next; } e[400010]; long long ans; void addedge(int x, int y) { e[++cnt] = (node){y, hd[x]}, hd[x] = cnt; e[++cnt] = (node){x, hd[y]}, hd[y] = cnt; } bool getpath(int x, int fa, int y, int o) { if (x == y) return t[o][++tn[o]] = x, 1; for (int i = hd[x]; i; i = e[i].next) if (e[i].to != fa && getpath(e[i].to, x, y, o)) return t[o][++tn[o]] = x, 1; return 0; } void bfs(int x) { memset(la, -1, sizeof(la)); q[l = r = 1] = x, la[x] = 0; while (l <= r) { x = q[l++]; for (int i = hd[x]; i; i = e[i].next) if (bo[e[i].to] && la[e[i].to] == -1) la[q[++r] = e[i].to] = x; } } int main() { scanf("%d", &n), cnt = 0, memset(hd, 0, sizeof(hd)), ans = 0; for (int i = 1; i <= n; i++) scanf("%d", &a[i]), pa[a[i]] = i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), pb[b[i]] = i; for (int i = 1; i < n; i++) scanf("%d%d", &x, &y), addedge(x, y); sa = pa[0], sb = pb[0]; while (1) { bool bo = 0; for (int i = hd[pa[0]]; i; i = e[i].next) if (a[e[i].to] == b[pa[0]]) { bo = 1, swap(a[pa[0]], a[e[i].to]), swap(pa[0], pa[a[pa[0]]]), ans++; break; } if (!bo) break; } while (1) { bool bo = 0; for (int i = hd[pb[0]]; i; i = e[i].next) if (b[e[i].to] == a[pb[0]]) { bo = 1, swap(b[pb[0]], b[e[i].to]), swap(pb[0], pb[b[pb[0]]]), ans++; break; } if (!bo) break; } if (pa[0] == pb[0]) { bool boo = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) { boo = 0; break; } if (boo) return printf("0 %lld\n", ans), 0; for (int i = 1; i <= n; i++) if (a[i] != b[i]) for (int j = hd[i]; j; j = e[j].next) if (a[e[j].to] != b[e[j].to]) d[i]++; int cnt = 0, Cnt = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i]) { if (d[i] == 1) cnt++; else if (d[i] == 0) Cnt++; else if (d[i] != 2) return puts("-1"), 0; } if (cnt / 2 + Cnt > 2) return puts("-1"), 0; int p = 0; if (cnt / 2 + Cnt == 1) { for (int i = 1; i <= n; i++) if (a[i] != b[i]) { p = i; break; } memset(bo, 0, sizeof(bo)); for (int i = 1; i <= n; i++) if (a[i] != b[i]) bo[i] = 1; bfs(p), bfs(q[r]); tn[0] = tn[1] = 0, getpath(q[r], 0, sa, 0), getpath(q[r], 0, sb, 1); if (t[0][tn[0] - 1] == t[1][tn[1] - 1] && !bo[t[0][tn[0] - 1]]) p = t[0][tn[0] - 1], tn[0]--, tn[1]--; else { tn[0] = tn[1] = 0, getpath(q[1], 0, sa, 0), getpath(q[1], 0, sb, 1); if (t[0][tn[0] - 1] == t[1][tn[1] - 1] && !bo[t[0][tn[0] - 1]]) p = t[0][tn[0] - 1], tn[0]--, tn[1]--; else return puts("-1"), 0; } } else { for (int i = 1; i <= n; i++) if (a[i] == b[i]) { cnt = 0; for (int j = hd[i]; j; j = e[j].next) if (a[e[j].to] != b[e[j].to]) cnt++; if (cnt == 2) { p = i; break; } } if (!p) return puts("-1"), 0; tn[0] = tn[1] = 0, getpath(sa, 0, p, 0), getpath(sb, 0, p, 1); if (tn[0] > 1 && a[t[0][2]] != b[t[0][2]]) return puts("-1"), 0; if (tn[1] > 1 && a[t[1][2]] != b[t[1][2]]) return puts("-1"), 0; } ans = tn[0] + tn[1] - 2; memset(bo, 0, sizeof(bo)), bo[p] = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) bo[i] = 1; bfs(p), bfs(q[r]), cn = 0, sa = q[1], sb = q[r]; for (int i = 1; i <= r; i++) if (q[i] != p) c[++cn] = q[i]; int del = 0; for (int i = 2; i <= cn; i++) if (a[c[i]] == b[c[1]]) { del = i - 1; break; } for (int i = 2; i <= cn; i++) if (a[c[(i + del - 1) % cn + 1]] != b[c[i]]) return puts("-1"), 0; del = min(del, cn - del); if (sa > sb) swap(sa, sb); printf("%d %d %lld\n", sa, sb, ans + 1ll * del * (cn + 1)); } else { if (b[pa[0]] == a[pb[0]]) { bool boo = 1; for (int i = 1; i <= n; i++) if (i != pa[0] && i != pb[0] && a[i] != b[i]) { boo = 0; break; } if (boo) { if (pa[0] > pb[0]) swap(pa[0], pb[0]); return printf("%d %d %lld\n", pa[0], pb[0], ans + 1), 0; } } memset(bo, 0, sizeof(bo)); for (int i = 1; i <= n; i++) if (a[i] != b[i]) bo[i] = 1; int cnt1 = 0, cnt2 = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i]) { for (int j = hd[i]; j; j = e[j].next) if (a[e[j].to] != b[e[j].to]) d[i]++; if (d[i] == 1) cnt1++; else if (d[i] == 2) cnt2++; else return puts("-1"), 0; } if (cnt1 != 2) return puts("-1"), 0; bfs(pa[0]), bfs(q[r]), tn[0] = 0, getpath(pb[0], 0, pa[0], 0); int A = 0, B = 0; for (int i = 1; i <= r; i++) if (q[i] == pa[0]) A = i; for (int i = 1; i <= r; i++) if (q[i] == pb[0]) B = i; cn = Cn = 0; for (int i = 1; i <= r; i++) if (q[i] != pa[0]) c[++cn] = a[q[i]]; for (int i = 1; i <= r; i++) if (q[i] != pb[0]) C[++Cn] = b[q[i]]; int del = 0; for (int i = 2; i <= cn; i++) if (c[i] == C[1]) { del = i - 1; break; } for (int i = 2; i <= cn; i++) if (c[(i + del - 1) % cn + 1] != C[i]) return puts("-1"), 0; if (q[1] > q[r]) swap(q[1], q[r]); if (A < B) printf("%d %d %lld\n", q[1], q[r], ans + min(1ll * del * (cn + 1) + tn[0] - 1, 1ll * (cn - 1 - del) * (cn + 1) + r - tn[0] + 1)); else printf("%d %d %lld\n", q[1], q[r], ans + min(1ll * (del - 1) * (cn + 1) + r - tn[0] + 1, 1ll * (cn - del) * (cn + 1) + tn[0] - 1)); } return 0; }
### Prompt Please formulate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; bool bo[200010]; int la[200010], a[200010], b[200010], pa[200010], pb[200010], x, y, hd[200010], cnt, n, t[2][200010], tn[2], sa, sb, c[200010], cn, d[200010], q[200010], l, r, C[200010], Cn; struct node { int to, next; } e[400010]; long long ans; void addedge(int x, int y) { e[++cnt] = (node){y, hd[x]}, hd[x] = cnt; e[++cnt] = (node){x, hd[y]}, hd[y] = cnt; } bool getpath(int x, int fa, int y, int o) { if (x == y) return t[o][++tn[o]] = x, 1; for (int i = hd[x]; i; i = e[i].next) if (e[i].to != fa && getpath(e[i].to, x, y, o)) return t[o][++tn[o]] = x, 1; return 0; } void bfs(int x) { memset(la, -1, sizeof(la)); q[l = r = 1] = x, la[x] = 0; while (l <= r) { x = q[l++]; for (int i = hd[x]; i; i = e[i].next) if (bo[e[i].to] && la[e[i].to] == -1) la[q[++r] = e[i].to] = x; } } int main() { scanf("%d", &n), cnt = 0, memset(hd, 0, sizeof(hd)), ans = 0; for (int i = 1; i <= n; i++) scanf("%d", &a[i]), pa[a[i]] = i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), pb[b[i]] = i; for (int i = 1; i < n; i++) scanf("%d%d", &x, &y), addedge(x, y); sa = pa[0], sb = pb[0]; while (1) { bool bo = 0; for (int i = hd[pa[0]]; i; i = e[i].next) if (a[e[i].to] == b[pa[0]]) { bo = 1, swap(a[pa[0]], a[e[i].to]), swap(pa[0], pa[a[pa[0]]]), ans++; break; } if (!bo) break; } while (1) { bool bo = 0; for (int i = hd[pb[0]]; i; i = e[i].next) if (b[e[i].to] == a[pb[0]]) { bo = 1, swap(b[pb[0]], b[e[i].to]), swap(pb[0], pb[b[pb[0]]]), ans++; break; } if (!bo) break; } if (pa[0] == pb[0]) { bool boo = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) { boo = 0; break; } if (boo) return printf("0 %lld\n", ans), 0; for (int i = 1; i <= n; i++) if (a[i] != b[i]) for (int j = hd[i]; j; j = e[j].next) if (a[e[j].to] != b[e[j].to]) d[i]++; int cnt = 0, Cnt = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i]) { if (d[i] == 1) cnt++; else if (d[i] == 0) Cnt++; else if (d[i] != 2) return puts("-1"), 0; } if (cnt / 2 + Cnt > 2) return puts("-1"), 0; int p = 0; if (cnt / 2 + Cnt == 1) { for (int i = 1; i <= n; i++) if (a[i] != b[i]) { p = i; break; } memset(bo, 0, sizeof(bo)); for (int i = 1; i <= n; i++) if (a[i] != b[i]) bo[i] = 1; bfs(p), bfs(q[r]); tn[0] = tn[1] = 0, getpath(q[r], 0, sa, 0), getpath(q[r], 0, sb, 1); if (t[0][tn[0] - 1] == t[1][tn[1] - 1] && !bo[t[0][tn[0] - 1]]) p = t[0][tn[0] - 1], tn[0]--, tn[1]--; else { tn[0] = tn[1] = 0, getpath(q[1], 0, sa, 0), getpath(q[1], 0, sb, 1); if (t[0][tn[0] - 1] == t[1][tn[1] - 1] && !bo[t[0][tn[0] - 1]]) p = t[0][tn[0] - 1], tn[0]--, tn[1]--; else return puts("-1"), 0; } } else { for (int i = 1; i <= n; i++) if (a[i] == b[i]) { cnt = 0; for (int j = hd[i]; j; j = e[j].next) if (a[e[j].to] != b[e[j].to]) cnt++; if (cnt == 2) { p = i; break; } } if (!p) return puts("-1"), 0; tn[0] = tn[1] = 0, getpath(sa, 0, p, 0), getpath(sb, 0, p, 1); if (tn[0] > 1 && a[t[0][2]] != b[t[0][2]]) return puts("-1"), 0; if (tn[1] > 1 && a[t[1][2]] != b[t[1][2]]) return puts("-1"), 0; } ans = tn[0] + tn[1] - 2; memset(bo, 0, sizeof(bo)), bo[p] = 1; for (int i = 1; i <= n; i++) if (a[i] != b[i]) bo[i] = 1; bfs(p), bfs(q[r]), cn = 0, sa = q[1], sb = q[r]; for (int i = 1; i <= r; i++) if (q[i] != p) c[++cn] = q[i]; int del = 0; for (int i = 2; i <= cn; i++) if (a[c[i]] == b[c[1]]) { del = i - 1; break; } for (int i = 2; i <= cn; i++) if (a[c[(i + del - 1) % cn + 1]] != b[c[i]]) return puts("-1"), 0; del = min(del, cn - del); if (sa > sb) swap(sa, sb); printf("%d %d %lld\n", sa, sb, ans + 1ll * del * (cn + 1)); } else { if (b[pa[0]] == a[pb[0]]) { bool boo = 1; for (int i = 1; i <= n; i++) if (i != pa[0] && i != pb[0] && a[i] != b[i]) { boo = 0; break; } if (boo) { if (pa[0] > pb[0]) swap(pa[0], pb[0]); return printf("%d %d %lld\n", pa[0], pb[0], ans + 1), 0; } } memset(bo, 0, sizeof(bo)); for (int i = 1; i <= n; i++) if (a[i] != b[i]) bo[i] = 1; int cnt1 = 0, cnt2 = 0; for (int i = 1; i <= n; i++) if (a[i] != b[i]) { for (int j = hd[i]; j; j = e[j].next) if (a[e[j].to] != b[e[j].to]) d[i]++; if (d[i] == 1) cnt1++; else if (d[i] == 2) cnt2++; else return puts("-1"), 0; } if (cnt1 != 2) return puts("-1"), 0; bfs(pa[0]), bfs(q[r]), tn[0] = 0, getpath(pb[0], 0, pa[0], 0); int A = 0, B = 0; for (int i = 1; i <= r; i++) if (q[i] == pa[0]) A = i; for (int i = 1; i <= r; i++) if (q[i] == pb[0]) B = i; cn = Cn = 0; for (int i = 1; i <= r; i++) if (q[i] != pa[0]) c[++cn] = a[q[i]]; for (int i = 1; i <= r; i++) if (q[i] != pb[0]) C[++Cn] = b[q[i]]; int del = 0; for (int i = 2; i <= cn; i++) if (c[i] == C[1]) { del = i - 1; break; } for (int i = 2; i <= cn; i++) if (c[(i + del - 1) % cn + 1] != C[i]) return puts("-1"), 0; if (q[1] > q[r]) swap(q[1], q[r]); if (A < B) printf("%d %d %lld\n", q[1], q[r], ans + min(1ll * del * (cn + 1) + tn[0] - 1, 1ll * (cn - 1 - del) * (cn + 1) + r - tn[0] + 1)); else printf("%d %d %lld\n", q[1], q[r], ans + min(1ll * (del - 1) * (cn + 1) + r - tn[0] + 1, 1ll * (cn - del) * (cn + 1) + tn[0] - 1)); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 200000 + 10; const long long inf = 1000000000000000; int a[maxn], b[maxn], c[maxn], cc[maxn], e[maxn], sta[maxn]; int h[maxn], go[maxn * 2], nxt[maxn * 2], fa[maxn], d[maxn]; int i, j, k, l, r, t, n, m, u, v, w, z, tot, top, S, T, ansu, ansv; long long num, sum, ans; bool bz[maxn]; bool czy; int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } void add(int x, int y) { go[++tot] = y; nxt[tot] = h[x]; h[x] = tot; } void dfs(int x, int y) { d[x] = d[y] + 1; fa[x] = y; int t = h[x]; while (t) { if (go[t] != y) dfs(go[t], x); t = nxt[t]; } } bool pd() { int i; for (i = 1; i <= n; i++) if (a[i] != b[i]) return 0; return 1; } void re() { int i; for (i = 1; i <= n; i++) { a[i] = c[i]; b[i] = cc[i]; } num = 0; } int lca(int x, int y) { while (x != y) { if (d[x] > d[y]) x = fa[x]; else y = fa[y]; } return x; } int main() { n = read(); for (i = 1; i <= n; i++) { c[i] = a[i] = read(); if (!a[i]) S = i; } for (i = 1; i <= n; i++) { cc[i] = b[i] = read(); if (!b[i]) T = i; } for (i = 1; i <= n - 1; i++) { j = read(); k = read(); add(j, k); add(k, j); } d[0] = -1; dfs(S, 0); k = T; while (k) { bz[k] = 1; sta[++top] = k; k = fa[k]; } for (i = 1; i <= top - 1; i++) b[sta[i]] = b[sta[i + 1]]; b[sta[top]] = 0; if (pd()) { printf("0 %d\n", d[T]); return 0; } ans = inf; num = d[T]; u = 0; v = 0; for (i = 1; i <= n; i++) if (a[i] != b[i]) { czy = 1; t = h[i]; while (t) { if (go[t] != fa[i] && a[go[t]] != b[go[t]]) { czy = 0; break; } t = nxt[t]; } if (!czy) continue; if (!u) u = i; else v = i; } if (!v) { k = u; top = 0; while (a[k] != b[k]) { sta[++top] = k; k = fa[k]; } l = k; while (!bz[l]) l = fa[l]; num += 2 * (d[k] - d[l]); for (i = 1; i <= top + 1; i++) if (i > top || b[sta[i]] == a[u]) break; if (i <= top) { for (j = 1; j <= top; j++) e[j] = a[sta[j]]; t = 0; for (j = i; j <= top; j++) a[sta[j]] = e[++t]; for (j = 1; j <= i - 1; j++) a[sta[j]] = e[++t]; if (pd()) { sum = num + (long long)(top + 1) * (i - 1); if (sum < ans) { ansu = k; ansv = u; ans = sum; } r = lca(u, T); sum = num + (long long)(top + 1) * (top - i + 1); if (d[r] > d[k]) sum -= (long long)2 * (d[r] - d[k]); if (sum < ans) { ansu = k; ansv = u; ans = sum; } } } } else { w = lca(u, v); l = w; while (!bz[l]) l = fa[l]; num += 2 * (d[w] - d[l]); top = 0; k = u; while (k != w) { if (fa[k] == w) r = k; sta[++top] = k; k = fa[k]; } reverse(sta + 1, sta + top + 1); k = v; while (k != w) { sta[++top] = k; k = fa[k]; } for (i = 1; i <= top + 1; i++) if (i > top || b[sta[i]] == a[r]) break; if (i <= top) { for (j = 1; j <= top; j++) e[j] = a[sta[j]]; t = 0; for (j = i; j <= top; j++) a[sta[j]] = e[++t]; for (j = 1; j <= i - 1; j++) a[sta[j]] = e[++t]; if (pd()) { r = lca(u, T); sum = num + (long long)(top + 1) * (i - 1); if (d[r] > d[w]) sum -= (long long)2 * (d[r] - d[w]); if (sum < ans) { ansu = u; ansv = v; ans = sum; } r = lca(v, T); sum = num + (long long)(top + 1) * (top - i + 1); if (d[r] > d[w]) sum -= (long long)2 * (d[r] - d[w]); if (sum < ans) { ansu = u; ansv = v; ans = sum; } } } } if (ans == inf) printf("-1\n"); else { if (ansu > ansv) swap(ansu, ansv); printf("%d %d %lld\n", ansu, ansv, ans); } }
### Prompt Please formulate a CPP solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 200000 + 10; const long long inf = 1000000000000000; int a[maxn], b[maxn], c[maxn], cc[maxn], e[maxn], sta[maxn]; int h[maxn], go[maxn * 2], nxt[maxn * 2], fa[maxn], d[maxn]; int i, j, k, l, r, t, n, m, u, v, w, z, tot, top, S, T, ansu, ansv; long long num, sum, ans; bool bz[maxn]; bool czy; int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } void add(int x, int y) { go[++tot] = y; nxt[tot] = h[x]; h[x] = tot; } void dfs(int x, int y) { d[x] = d[y] + 1; fa[x] = y; int t = h[x]; while (t) { if (go[t] != y) dfs(go[t], x); t = nxt[t]; } } bool pd() { int i; for (i = 1; i <= n; i++) if (a[i] != b[i]) return 0; return 1; } void re() { int i; for (i = 1; i <= n; i++) { a[i] = c[i]; b[i] = cc[i]; } num = 0; } int lca(int x, int y) { while (x != y) { if (d[x] > d[y]) x = fa[x]; else y = fa[y]; } return x; } int main() { n = read(); for (i = 1; i <= n; i++) { c[i] = a[i] = read(); if (!a[i]) S = i; } for (i = 1; i <= n; i++) { cc[i] = b[i] = read(); if (!b[i]) T = i; } for (i = 1; i <= n - 1; i++) { j = read(); k = read(); add(j, k); add(k, j); } d[0] = -1; dfs(S, 0); k = T; while (k) { bz[k] = 1; sta[++top] = k; k = fa[k]; } for (i = 1; i <= top - 1; i++) b[sta[i]] = b[sta[i + 1]]; b[sta[top]] = 0; if (pd()) { printf("0 %d\n", d[T]); return 0; } ans = inf; num = d[T]; u = 0; v = 0; for (i = 1; i <= n; i++) if (a[i] != b[i]) { czy = 1; t = h[i]; while (t) { if (go[t] != fa[i] && a[go[t]] != b[go[t]]) { czy = 0; break; } t = nxt[t]; } if (!czy) continue; if (!u) u = i; else v = i; } if (!v) { k = u; top = 0; while (a[k] != b[k]) { sta[++top] = k; k = fa[k]; } l = k; while (!bz[l]) l = fa[l]; num += 2 * (d[k] - d[l]); for (i = 1; i <= top + 1; i++) if (i > top || b[sta[i]] == a[u]) break; if (i <= top) { for (j = 1; j <= top; j++) e[j] = a[sta[j]]; t = 0; for (j = i; j <= top; j++) a[sta[j]] = e[++t]; for (j = 1; j <= i - 1; j++) a[sta[j]] = e[++t]; if (pd()) { sum = num + (long long)(top + 1) * (i - 1); if (sum < ans) { ansu = k; ansv = u; ans = sum; } r = lca(u, T); sum = num + (long long)(top + 1) * (top - i + 1); if (d[r] > d[k]) sum -= (long long)2 * (d[r] - d[k]); if (sum < ans) { ansu = k; ansv = u; ans = sum; } } } } else { w = lca(u, v); l = w; while (!bz[l]) l = fa[l]; num += 2 * (d[w] - d[l]); top = 0; k = u; while (k != w) { if (fa[k] == w) r = k; sta[++top] = k; k = fa[k]; } reverse(sta + 1, sta + top + 1); k = v; while (k != w) { sta[++top] = k; k = fa[k]; } for (i = 1; i <= top + 1; i++) if (i > top || b[sta[i]] == a[r]) break; if (i <= top) { for (j = 1; j <= top; j++) e[j] = a[sta[j]]; t = 0; for (j = i; j <= top; j++) a[sta[j]] = e[++t]; for (j = 1; j <= i - 1; j++) a[sta[j]] = e[++t]; if (pd()) { r = lca(u, T); sum = num + (long long)(top + 1) * (i - 1); if (d[r] > d[w]) sum -= (long long)2 * (d[r] - d[w]); if (sum < ans) { ansu = u; ansv = v; ans = sum; } r = lca(v, T); sum = num + (long long)(top + 1) * (top - i + 1); if (d[r] > d[w]) sum -= (long long)2 * (d[r] - d[w]); if (sum < ans) { ansu = u; ansv = v; ans = sum; } } } } if (ans == inf) printf("-1\n"); else { if (ansu > ansv) swap(ansu, ansv); printf("%d %d %lld\n", ansu, ansv, ans); } } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> sosedi[maxn]; int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n; void dfs(int v, int predok) { parent[v] = predok; shagi[v] = shagi[predok] + 1; for (auto p : sosedi[v]) if (p != predok) dfs(p, v); } vector<int> circles; int rt, lp, lq; bool find_circle() { circles.clear(); static bool visit_vertex[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && shagi[i] > shagi[p]) p = i; if (!p) return 1; for (int u = p; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[q]) q = i; if (q) { reverse(circles.begin(), circles.end()); for (int u = q; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; } else q = parent[circles.back()]; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i]) return 0; int u, v; for (u = p, v = q; u != v; u = parent[u]) if (shagi[u] < shagi[v]) swap(u, v); rt = u; if (circles.size() != shagi[p] + shagi[q] - 2 * shagi[rt]) return 0; lp = p, lq = q; return 1; } int main() { cin >> n; int pa, pb; for (int i = 1; i <= n; i++) { cin >> start[i]; if (start[i] == 0) pa = i; } for (int i = 1; i <= n; i++) { cin >> finish[i]; if (finish[i] == 0) pb = i; } for (int i = 1, u, v; i < n; i++) { cin >> u >> v; sosedi[u].push_back(v), sosedi[v].push_back(u); } shagi[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = parent[u]) swap(start[u], start[parent[u]]); long long ans = shagi[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!circles.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = circles.size(); for (int i = 0; i < len; i++) if (finish[circles[i]] == start[circles[0]]) gap = i; for (int i = 1; i < len; i++) if (finish[circles[(i + gap) % len]] != start[circles[i]]) { printf("-1\n"); return 0; } static bool visit_vertex[maxn]; for (int i = pa; i; i = parent[i]) visit_vertex[i] = 1; if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) { int po = circles.size(); for (int i = 0; i < circles.size(); i++) if (!visit_vertex[circles[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !visit_vertex[rt]; rt = parent[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; }
### Prompt Develop a solution in cpp to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 200005; vector<int> sosedi[maxn]; int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n; void dfs(int v, int predok) { parent[v] = predok; shagi[v] = shagi[predok] + 1; for (auto p : sosedi[v]) if (p != predok) dfs(p, v); } vector<int> circles; int rt, lp, lq; bool find_circle() { circles.clear(); static bool visit_vertex[maxn]; int p = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && shagi[i] > shagi[p]) p = i; if (!p) return 1; for (int u = p; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; int q = 0; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[q]) q = i; if (q) { reverse(circles.begin(), circles.end()); for (int u = q; visit_vertex[u] = 1, circles.push_back(u), start[parent[u]] != finish[parent[u]]; u = parent[u]) ; } else q = parent[circles.back()]; for (int i = 1; i <= n; i++) if (start[i] != finish[i] && !visit_vertex[i]) return 0; int u, v; for (u = p, v = q; u != v; u = parent[u]) if (shagi[u] < shagi[v]) swap(u, v); rt = u; if (circles.size() != shagi[p] + shagi[q] - 2 * shagi[rt]) return 0; lp = p, lq = q; return 1; } int main() { cin >> n; int pa, pb; for (int i = 1; i <= n; i++) { cin >> start[i]; if (start[i] == 0) pa = i; } for (int i = 1; i <= n; i++) { cin >> finish[i]; if (finish[i] == 0) pb = i; } for (int i = 1, u, v; i < n; i++) { cin >> u >> v; sosedi[u].push_back(v), sosedi[v].push_back(u); } shagi[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = parent[u]) swap(start[u], start[parent[u]]); long long ans = shagi[pa]; if (!find_circle()) { printf("-1\n"); return 0; } if (!circles.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = circles.size(); for (int i = 0; i < len; i++) if (finish[circles[i]] == start[circles[0]]) gap = i; for (int i = 1; i < len; i++) if (finish[circles[(i + gap) % len]] != start[circles[i]]) { printf("-1\n"); return 0; } static bool visit_vertex[maxn]; for (int i = pa; i; i = parent[i]) visit_vertex[i] = 1; if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) { int po = circles.size(); for (int i = 0; i < circles.size(); i++) if (!visit_vertex[circles[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !visit_vertex[rt]; rt = parent[rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 200100; vector<int> g[N]; int a[N], b[N], p[N], q[N], n, s, t, ans_u, ans_v, cnt; void gofail() { cout << -1 << '\n'; exit(0); } int chk(int* a, int* b, int n) { for (int i = 1; i <= n; ++i) if (b[i] == a[1]) { for (int j = 0; j < n; ++j) if (a[j % n + 1] != b[(i - 1 + j) % n + 1]) return -1; return i - 1; } return -1; } int fa[N], dp[N]; void dfs(int x) { for (int i : g[x]) if (i != fa[x]) { fa[i] = x; dp[i] = dp[x] + 1; dfs(i); } } int lca(int x, int y) { for (; x != y; x = fa[x]) if (dp[x] < dp[y]) swap(x, y); return x; } int dis(int x, int y) { return dp[x] + dp[y] - 2 * dp[lca(x, y)]; } int vis[N]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (!a[i]) s = i; } for (int i = 1; i <= n; ++i) { cin >> b[i]; if (!b[i]) t = i; } for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } dfs(t); int rs = s; for (; s != t; s = fa[s]) swap(a[s], a[fa[s]]); int lst = 0, hst = 0; for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { ++cnt; if (!lst || dp[i] > dp[lst]) lst = i; if (!hst || dp[i] < dp[hst]) hst = i; } if (!lst) { cout << 0 << ' ' << dis(rs, t) << '\n'; return 0; } if (hst == t) gofail(); hst = fa[hst]; int tt = 0, ww = cnt + 1; for (int i = lst; i && i != hst; i = fa[i]) { if (a[i] == b[i]) gofail(); p[++tt] = a[i]; q[tt] = b[i]; vis[i] = 1; } ans_u = lst; lst = 0; for (int i = 1; i <= n; ++i) if (a[i] != b[i] && !vis[i] && (!lst || dp[i] > dp[lst])) lst = i; if (!lst) ans_v = hst; else { for (int i = lst; i && i != hst; i = fa[i]) { if (a[i] == b[i] || vis[i]) gofail(); p[--ww] = a[i]; q[ww] = b[i]; vis[i] = 1; } if (tt + 1 != ww) gofail(); ans_v = lst; } if (ans_u > ans_v) { swap(ans_u, ans_v); reverse(p + 1, p + cnt + 1); reverse(q + 1, q + cnt + 1); } int res = chk(p, q, cnt); if (res == -1) gofail(); cout << ans_u << ' ' << ans_v << ' ' << min(dis(rs, ans_u) + (long long)(res - 1) * (dis(ans_v, ans_u) + 1) + 1 + dis(ans_v, t), dis(rs, ans_v) + (long long)(cnt - res - 1) * (dis(ans_v, ans_u) + 1) + 1 + dis(ans_u, t)) << '\n'; return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200100; vector<int> g[N]; int a[N], b[N], p[N], q[N], n, s, t, ans_u, ans_v, cnt; void gofail() { cout << -1 << '\n'; exit(0); } int chk(int* a, int* b, int n) { for (int i = 1; i <= n; ++i) if (b[i] == a[1]) { for (int j = 0; j < n; ++j) if (a[j % n + 1] != b[(i - 1 + j) % n + 1]) return -1; return i - 1; } return -1; } int fa[N], dp[N]; void dfs(int x) { for (int i : g[x]) if (i != fa[x]) { fa[i] = x; dp[i] = dp[x] + 1; dfs(i); } } int lca(int x, int y) { for (; x != y; x = fa[x]) if (dp[x] < dp[y]) swap(x, y); return x; } int dis(int x, int y) { return dp[x] + dp[y] - 2 * dp[lca(x, y)]; } int vis[N]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (!a[i]) s = i; } for (int i = 1; i <= n; ++i) { cin >> b[i]; if (!b[i]) t = i; } for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } dfs(t); int rs = s; for (; s != t; s = fa[s]) swap(a[s], a[fa[s]]); int lst = 0, hst = 0; for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { ++cnt; if (!lst || dp[i] > dp[lst]) lst = i; if (!hst || dp[i] < dp[hst]) hst = i; } if (!lst) { cout << 0 << ' ' << dis(rs, t) << '\n'; return 0; } if (hst == t) gofail(); hst = fa[hst]; int tt = 0, ww = cnt + 1; for (int i = lst; i && i != hst; i = fa[i]) { if (a[i] == b[i]) gofail(); p[++tt] = a[i]; q[tt] = b[i]; vis[i] = 1; } ans_u = lst; lst = 0; for (int i = 1; i <= n; ++i) if (a[i] != b[i] && !vis[i] && (!lst || dp[i] > dp[lst])) lst = i; if (!lst) ans_v = hst; else { for (int i = lst; i && i != hst; i = fa[i]) { if (a[i] == b[i] || vis[i]) gofail(); p[--ww] = a[i]; q[ww] = b[i]; vis[i] = 1; } if (tt + 1 != ww) gofail(); ans_v = lst; } if (ans_u > ans_v) { swap(ans_u, ans_v); reverse(p + 1, p + cnt + 1); reverse(q + 1, q + cnt + 1); } int res = chk(p, q, cnt); if (res == -1) gofail(); cout << ans_u << ' ' << ans_v << ' ' << min(dis(rs, ans_u) + (long long)(res - 1) * (dis(ans_v, ans_u) + 1) + 1 + dis(ans_v, t), dis(rs, ans_v) + (long long)(cnt - res - 1) * (dis(ans_v, ans_u) + 1) + 1 + dis(ans_u, t)) << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; vector<int> v[200010], circle; int fa[200010], dep[200010], a[200010], b[200010], n, rt, vs, vt, h1, h2; bool vis[200010], bo[200010]; inline int rd() { int x = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) ; for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; return x; } inline void dfs(int x) { for (int i = 0, siz = v[x].size(); i < siz; i++) { int t = v[x][i]; if (t == fa[x]) continue; dep[t] = dep[x] + 1; fa[t] = x; dfs(t); } } inline bool gao() { int p = 0, q = 0; bool flag = true; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return true; for (int hh = p; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i] && dep[i] > dep[q]) q = i; if (q) { reverse(circle.begin(), circle.end()); flag = false; for (int hh = q; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); } else q = fa[circle.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i]) return false; int h1 = p, h2 = q; for (; h1 != h2; h1 = fa[h1]) if (dep[h1] < dep[h2]) swap(h1, h2); rt = h1; if (circle.size() != dep[p] + dep[q] - dep[rt] * 2) return false; vs = p; vt = q; if (flag) reverse(circle.begin(), circle.end()); return true; } int main() { n = rd(); for (int i = 1; i <= n; i++) if (!(a[i] = rd())) h1 = i; for (int i = 1; i <= n; i++) if (!(b[i] = rd())) h2 = i; for (int i = 1; i < n; i++) { int x = rd(), y = rd(); v[x].push_back(y); v[y].push_back(x); } dep[0] = -1; dfs(h2); for (int hh = h1; hh != h2; hh = fa[hh]) swap(a[hh], a[fa[hh]]); long long ans = dep[h1]; if (!gao()) { puts("-1"); return 0; } if (!circle.size()) { printf("0 %d\n", ans); return 0; } for (int i = h1; i; i = fa[i]) vis[i] = true; if (vis[circle.back()] && !vis[circle[0]]) reverse(circle.begin(), circle.end()); int gap = 0, siz = circle.size(); for (int i = 0; i < siz; i++) if (b[circle[i]] == a[circle[0]]) gap = i; for (int i = 0; i < siz; i++) if (b[circle[(i + gap) % siz]] != a[circle[i]]) { puts("-1"); return 0; } if (vis[circle[0]] || vis[circle.back()]) { int now = siz; for (int i = 0; i < siz; i++) if (!vis[circle[i]]) { now = i; break; } ans = ans - now + min((long long)gap * (siz + 1) + now, abs((long long)(siz - gap) * (siz + 1) - now)); } else ans = (ans + (long long)min(gap, siz - gap) * (siz + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (vs > vt) swap(vs, vt); printf("%d %d %I64d\n", vs, vt, ans); return 0; }
### Prompt Create a solution in Cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<int> v[200010], circle; int fa[200010], dep[200010], a[200010], b[200010], n, rt, vs, vt, h1, h2; bool vis[200010], bo[200010]; inline int rd() { int x = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) ; for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; return x; } inline void dfs(int x) { for (int i = 0, siz = v[x].size(); i < siz; i++) { int t = v[x][i]; if (t == fa[x]) continue; dep[t] = dep[x] + 1; fa[t] = x; dfs(t); } } inline bool gao() { int p = 0, q = 0; bool flag = true; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return true; for (int hh = p; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i] && dep[i] > dep[q]) q = i; if (q) { reverse(circle.begin(), circle.end()); flag = false; for (int hh = q; a[hh] != b[hh]; hh = fa[hh]) bo[hh] = true, circle.push_back(hh); } else q = fa[circle.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !bo[i]) return false; int h1 = p, h2 = q; for (; h1 != h2; h1 = fa[h1]) if (dep[h1] < dep[h2]) swap(h1, h2); rt = h1; if (circle.size() != dep[p] + dep[q] - dep[rt] * 2) return false; vs = p; vt = q; if (flag) reverse(circle.begin(), circle.end()); return true; } int main() { n = rd(); for (int i = 1; i <= n; i++) if (!(a[i] = rd())) h1 = i; for (int i = 1; i <= n; i++) if (!(b[i] = rd())) h2 = i; for (int i = 1; i < n; i++) { int x = rd(), y = rd(); v[x].push_back(y); v[y].push_back(x); } dep[0] = -1; dfs(h2); for (int hh = h1; hh != h2; hh = fa[hh]) swap(a[hh], a[fa[hh]]); long long ans = dep[h1]; if (!gao()) { puts("-1"); return 0; } if (!circle.size()) { printf("0 %d\n", ans); return 0; } for (int i = h1; i; i = fa[i]) vis[i] = true; if (vis[circle.back()] && !vis[circle[0]]) reverse(circle.begin(), circle.end()); int gap = 0, siz = circle.size(); for (int i = 0; i < siz; i++) if (b[circle[i]] == a[circle[0]]) gap = i; for (int i = 0; i < siz; i++) if (b[circle[(i + gap) % siz]] != a[circle[i]]) { puts("-1"); return 0; } if (vis[circle[0]] || vis[circle.back()]) { int now = siz; for (int i = 0; i < siz; i++) if (!vis[circle[i]]) { now = i; break; } ans = ans - now + min((long long)gap * (siz + 1) + now, abs((long long)(siz - gap) * (siz + 1) - now)); } else ans = (ans + (long long)min(gap, siz - gap) * (siz + 1)); for (; !vis[rt]; rt = fa[rt]) ans += 2; if (vs > vt) swap(vs, vt); printf("%d %d %I64d\n", vs, vt, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; namespace io { const int SI = 1 << 21 | 1; char IB[SI], *IS, *IT, OB[SI], *OS = OB, *OT = OS + SI - 1, c, ch[100]; int f, t; inline void flush() { fwrite(OB, 1, OS - OB, stdout), OS = OB; } inline void pc(char x) { *OS++ = x; if (OS == OT) flush(); } template <class I> inline void rd(I &x) { for (f = 1, c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++); c < '0' || c > '9'; c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) if (c == '-') f = -1; for (x = 0; c >= '0' && c <= '9'; x = (x << 3) + (x << 1) + (c & 15), c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) ; x *= f; } inline void rds(char *s, int &x) { for (c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++); c < 33 || c > 126; c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) ; for (x = 0; c >= 33 && c <= 126; s[++x] = c, c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) ; s[x + 1] = '\0'; } template <class I> inline void print(I x, char k = '\n') { if (!x) pc('0'); if (x < 0) pc('-'), x = -x; while (x) ch[++t] = x % 10 + '0', x /= 10; while (t) pc(ch[t--]); pc(k); } inline void prints(string s) { int x = s.length(); while (t < x) pc(s[t++]); pc('\n'), t = 0; } struct Flush { ~Flush() { flush(); } } flusher; } // namespace io using io::print; using io::prints; using io::rd; using io::rds; const int N = 2e5 + 7; int n, a[N], b[N], s, t, p, v[N], d[N]; vector<int> e[N], g, h, A, B; pair<int, int> o = make_pair(N, 0); bool dfs1(int x, int f) { g.push_back(x); if (x == t) return 1; for (auto y : e[x]) if (y != f && dfs1(y, x)) return 1; g.pop_back(); return 0; } void dfs2(int x, int f, int d) { if (a[x] != b[x]) { h.push_back(x), v[x] = 1; if (d - 1 == o.first && f != o.second) print(-1), exit(0); ; if (d - 1 < o.first) o = make_pair(d - 1, f); } for (auto y : e[x]) if (y != f) dfs2(y, x, d + 1); } void dfs3(int x, int f) { if (x != p) A.push_back(a[x]), B.push_back(b[x]); for (auto y : e[x]) if (y != f && v[y]) dfs3(y, x); } int dfs4(int x, int f, int d, int t) { if (x == t) return d; for (auto y : e[x]) if (y != f) { int o = dfs4(y, x, d + 1, t); if (o) return o; } return 0; } inline int calc(vector<int> A, vector<int> B) { int pos = 0, siz = A.size(); for (unsigned int i = 0; i < B.size(); i++) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (unsigned int i = 0; i < A.size(); i++) if (A[i] != B[(i + pos) % siz]) return 0; return pos; } inline int S(int x, int y) { return dfs4(x, 0, 0, y); } inline long long get(int x, int y) { int c = calc(A, B); return S(s, x) + 1ll * (c - 1) * (A.size() + 1) + 1 + S(y, t); } int main() { rd(n); for (int i = 1; i <= n; i++) rd(a[i]), s = a[i] ? s : i; for (int i = 1; i <= n; i++) rd(b[i]), t = b[i] ? t : i; for (int i = 1, x, y; i < n; i++) rd(x), rd(y), e[x].push_back(y), e[y].push_back(x); dfs1(s, 0); for (unsigned int i = 1; i < g.size(); i++) swap(a[g[i - 1]], a[g[i]]); bool ok = 1; for (int i = 1; i <= n; i++) ok &= a[i] == b[i]; if (ok) return print(0, ' '), print(g.size() - 1), 0; dfs2(t, 0, 0), h.push_back(p = o.second), v[p] = 1; for (auto x : h) for (auto y : e[x]) if (v[y]) ++d[x]; vector<int> u; for (auto x : h) if (d[x] == 1) u.push_back(x); else if (d[x] != 2) print(-1), exit(0); ; if (u.size() != 2u) print(-1), exit(0); ; if (u[0] > u[1]) swap(u[0], u[1]); dfs3(u[0], 0); if (!calc(A, B)) print(-1), exit(0); ; print(u[0], ' '), print(u[1], ' '); long long ans = get(u[0], u[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); print(min(ans, get(u[1], u[0]))); return 0; }
### Prompt Create a solution in CPP for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; namespace io { const int SI = 1 << 21 | 1; char IB[SI], *IS, *IT, OB[SI], *OS = OB, *OT = OS + SI - 1, c, ch[100]; int f, t; inline void flush() { fwrite(OB, 1, OS - OB, stdout), OS = OB; } inline void pc(char x) { *OS++ = x; if (OS == OT) flush(); } template <class I> inline void rd(I &x) { for (f = 1, c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++); c < '0' || c > '9'; c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) if (c == '-') f = -1; for (x = 0; c >= '0' && c <= '9'; x = (x << 3) + (x << 1) + (c & 15), c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) ; x *= f; } inline void rds(char *s, int &x) { for (c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++); c < 33 || c > 126; c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) ; for (x = 0; c >= 33 && c <= 126; s[++x] = c, c = (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)) ; s[x + 1] = '\0'; } template <class I> inline void print(I x, char k = '\n') { if (!x) pc('0'); if (x < 0) pc('-'), x = -x; while (x) ch[++t] = x % 10 + '0', x /= 10; while (t) pc(ch[t--]); pc(k); } inline void prints(string s) { int x = s.length(); while (t < x) pc(s[t++]); pc('\n'), t = 0; } struct Flush { ~Flush() { flush(); } } flusher; } // namespace io using io::print; using io::prints; using io::rd; using io::rds; const int N = 2e5 + 7; int n, a[N], b[N], s, t, p, v[N], d[N]; vector<int> e[N], g, h, A, B; pair<int, int> o = make_pair(N, 0); bool dfs1(int x, int f) { g.push_back(x); if (x == t) return 1; for (auto y : e[x]) if (y != f && dfs1(y, x)) return 1; g.pop_back(); return 0; } void dfs2(int x, int f, int d) { if (a[x] != b[x]) { h.push_back(x), v[x] = 1; if (d - 1 == o.first && f != o.second) print(-1), exit(0); ; if (d - 1 < o.first) o = make_pair(d - 1, f); } for (auto y : e[x]) if (y != f) dfs2(y, x, d + 1); } void dfs3(int x, int f) { if (x != p) A.push_back(a[x]), B.push_back(b[x]); for (auto y : e[x]) if (y != f && v[y]) dfs3(y, x); } int dfs4(int x, int f, int d, int t) { if (x == t) return d; for (auto y : e[x]) if (y != f) { int o = dfs4(y, x, d + 1, t); if (o) return o; } return 0; } inline int calc(vector<int> A, vector<int> B) { int pos = 0, siz = A.size(); for (unsigned int i = 0; i < B.size(); i++) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (unsigned int i = 0; i < A.size(); i++) if (A[i] != B[(i + pos) % siz]) return 0; return pos; } inline int S(int x, int y) { return dfs4(x, 0, 0, y); } inline long long get(int x, int y) { int c = calc(A, B); return S(s, x) + 1ll * (c - 1) * (A.size() + 1) + 1 + S(y, t); } int main() { rd(n); for (int i = 1; i <= n; i++) rd(a[i]), s = a[i] ? s : i; for (int i = 1; i <= n; i++) rd(b[i]), t = b[i] ? t : i; for (int i = 1, x, y; i < n; i++) rd(x), rd(y), e[x].push_back(y), e[y].push_back(x); dfs1(s, 0); for (unsigned int i = 1; i < g.size(); i++) swap(a[g[i - 1]], a[g[i]]); bool ok = 1; for (int i = 1; i <= n; i++) ok &= a[i] == b[i]; if (ok) return print(0, ' '), print(g.size() - 1), 0; dfs2(t, 0, 0), h.push_back(p = o.second), v[p] = 1; for (auto x : h) for (auto y : e[x]) if (v[y]) ++d[x]; vector<int> u; for (auto x : h) if (d[x] == 1) u.push_back(x); else if (d[x] != 2) print(-1), exit(0); ; if (u.size() != 2u) print(-1), exit(0); ; if (u[0] > u[1]) swap(u[0], u[1]); dfs3(u[0], 0); if (!calc(A, B)) print(-1), exit(0); ; print(u[0], ' '), print(u[1], ' '); long long ans = get(u[0], u[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); print(min(ans, get(u[1], u[0]))); return 0; } ```
#include <bits/stdc++.h> using namespace std; void gg() { printf("-1\n"); exit(0); return; } int n; struct Edge { int v, nxt; } e[400010]; int tot; int first[200010]; void build(int u, int v) { e[++tot] = (Edge){v, first[u]}; first[u] = tot; return; } int a[200010], b[200010]; int fa[200010]; int dis[200010]; int pos[200010]; void dfs1(int u, int lst) { fa[u] = lst; if (lst) dis[u] = dis[lst] + 1; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != lst) dfs1(e[i].v, u); return; } bool vis[200010]; void work1() { int x = pos[1]; int res = dis[x]; while (x != 1) { vis[x] = true; swap(b[x], b[fa[x]]); x = fa[x]; } vis[1] = true; for (int i = 1; i <= n; i++) if (b[i] != i) return; printf("0 %d\n", res); exit(0); } vector<int> vec[2]; int num = 0; void getpath(int u) { if (num == 2 || (num == 1 && fa[u] != fa[vec[0][0]])) gg(); while (u) { vec[num].push_back(u); int v = 0; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u] && b[e[i].v] != e[i].v) { if (!v) v = e[i].v; else gg(); } u = v; } num++; } void dfs2(int u) { for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u]) { if (b[e[i].v] == e[i].v) dfs2(e[i].v); else getpath(e[i].v); } return; } int tmp[200010]; int ori[200010]; void work2() { int u, v, x; if (num == 1) { x = u = fa[vec[0][0]]; v = vec[0][vec[0].size() - 1]; } else { x = fa[vec[0][0]]; u = vec[0][vec[0].size() - 1]; v = vec[1][vec[1].size() - 1]; for (int i = 1; i <= vec[1].size(); i++) vec[0].push_back(vec[1][vec[1].size() - i]); } memset(tmp, -1, sizeof(tmp)); int k = 0, num = vec[0].size(); for (int i = 0; i < num; i++) { int o = vec[0][i]; tmp[o] = i; } for (int i = 1; i <= n; i++) if (tmp[i] == -1 && b[i] != i) gg(); for (int i = 0; i < num; i++) { int o = vec[0][i]; int val = (tmp[b[o]] + num - i) % num; if (i == 0) k = val; else if (k != val) gg(); } int dist = dis[u] + dis[v] - dis[x] * 2 + 1; long long ans; if (!vis[x]) { k = min(k, num - k); ans = (long long)k * dist; while (!vis[x]) ans += 2, x = fa[x]; ans += dis[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { int o = vec[0][i]; cnt += vis[o]; } if (vis[vec[0][0]]) ans = min(dist * k, dist * (num - k) - 2 * cnt) + dis[pos[1]]; else ans = min(dist * k - 2 * cnt, dist * (num - k)) + dis[pos[1]]; } u = ori[u]; v = ori[v]; if (u > v) swap(u, v); printf("%d %d %I64d\n", u, v, ans); return; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); u = a[u]; v = a[v]; build(u, v); build(v, u); } dfs1(1, 0); work1(); dfs2(1); work2(); return 0; }
### Prompt Develop a solution in cpp to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void gg() { printf("-1\n"); exit(0); return; } int n; struct Edge { int v, nxt; } e[400010]; int tot; int first[200010]; void build(int u, int v) { e[++tot] = (Edge){v, first[u]}; first[u] = tot; return; } int a[200010], b[200010]; int fa[200010]; int dis[200010]; int pos[200010]; void dfs1(int u, int lst) { fa[u] = lst; if (lst) dis[u] = dis[lst] + 1; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != lst) dfs1(e[i].v, u); return; } bool vis[200010]; void work1() { int x = pos[1]; int res = dis[x]; while (x != 1) { vis[x] = true; swap(b[x], b[fa[x]]); x = fa[x]; } vis[1] = true; for (int i = 1; i <= n; i++) if (b[i] != i) return; printf("0 %d\n", res); exit(0); } vector<int> vec[2]; int num = 0; void getpath(int u) { if (num == 2 || (num == 1 && fa[u] != fa[vec[0][0]])) gg(); while (u) { vec[num].push_back(u); int v = 0; for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u] && b[e[i].v] != e[i].v) { if (!v) v = e[i].v; else gg(); } u = v; } num++; } void dfs2(int u) { for (int i = first[u]; i; i = e[i].nxt) if (e[i].v != fa[u]) { if (b[e[i].v] == e[i].v) dfs2(e[i].v); else getpath(e[i].v); } return; } int tmp[200010]; int ori[200010]; void work2() { int u, v, x; if (num == 1) { x = u = fa[vec[0][0]]; v = vec[0][vec[0].size() - 1]; } else { x = fa[vec[0][0]]; u = vec[0][vec[0].size() - 1]; v = vec[1][vec[1].size() - 1]; for (int i = 1; i <= vec[1].size(); i++) vec[0].push_back(vec[1][vec[1].size() - i]); } memset(tmp, -1, sizeof(tmp)); int k = 0, num = vec[0].size(); for (int i = 0; i < num; i++) { int o = vec[0][i]; tmp[o] = i; } for (int i = 1; i <= n; i++) if (tmp[i] == -1 && b[i] != i) gg(); for (int i = 0; i < num; i++) { int o = vec[0][i]; int val = (tmp[b[o]] + num - i) % num; if (i == 0) k = val; else if (k != val) gg(); } int dist = dis[u] + dis[v] - dis[x] * 2 + 1; long long ans; if (!vis[x]) { k = min(k, num - k); ans = (long long)k * dist; while (!vis[x]) ans += 2, x = fa[x]; ans += dis[pos[1]]; } else { int cnt = 0; for (int i = 0; i < num; i++) { int o = vec[0][i]; cnt += vis[o]; } if (vis[vec[0][0]]) ans = min(dist * k, dist * (num - k) - 2 * cnt) + dis[pos[1]]; else ans = min(dist * k - 2 * cnt, dist * (num - k)) + dis[pos[1]]; } u = ori[u]; v = ori[v]; if (u > v) swap(u, v); printf("%d %d %I64d\n", u, v, ans); return; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); a[i]++; ori[a[i]] = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[a[i]]); b[a[i]]++; pos[b[a[i]]] = a[i]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); u = a[u]; v = a[v]; build(u, v); build(v, u); } dfs1(1, 0); work1(); dfs2(1); work2(); return 0; } ```
#include <bits/stdc++.h> using namespace std; int fx, vis[200002], c1[200002], c2[200002], c3[200002], c4[200002], t1, t2, t3, t4, xi, yi, pos[4], et = 1, e[200002], cd[200002 << 1], nt[200002 << 1], a[200002], b[200002], fa[200002], d[200002], n, wt, ss[19]; char fl[1 << 23], *A = fl; bool fg; bool u[200002]; void read(int& x) { char c; for (x = 0; '0' > (c = *A++) || c > '9';) ; while ('0' <= c && c <= '9') x = (x << 3) + (x << 1) + c - 48, (c = *A++); } void print(long long x) { if (!x) putchar(48); else { for (wt = 0; x; ss[++wt] = x % 10, x /= 10) ; for (; wt; putchar(ss[wt--] + 48)) ; } } void dfs(int x, int fe) { for (int y = e[x]; y; y = nt[y]) if (y != fe) fa[cd[y]] = x, d[cd[y]] = d[x] + 1, dfs(cd[y], y ^ 1); } void prin(int x, int y) { if (x < y) print(x), putchar(' '), print(y), putchar(' '); else print(y), putchar(' '), print(x), putchar(' '); } bool cmp(int x, int y) { return d[x] > d[y]; } long long min(long long a, long long b) { return a > b ? b : a; } int main() { int i, x, y, X, Y; long long tmp; for (*(fl + fread(fl, 1, 1 << 23, stdin)) = EOF, read(n), i = 1; i <= n; i++) if (read(a[i]), !a[i]) X = i; for (i = 1; i <= n; i++) if (read(b[i]), !b[i]) Y = i; for (i = 1; i < n; read(x), read(y), cd[++et] = y, nt[et] = e[x], e[x] = et, cd[++et] = x, nt[et] = e[y], e[y] = et, i++) ; for (dfs(X, 0), u[X] = true, y = Y; y != X; u[y] = true, swap(b[y], b[fa[y]]), y = fa[y]) ; for (i = 1; i <= n; i++) if (a[i] != b[i]) { int ti = 0; fg = true; for (y = e[i]; y && ti <= 1; y = nt[y]) if (a[cd[y]] != b[cd[y]]) ti++; if (ti <= 1) { for (x = 0; x < 4 && pos[x]; x++) ; if (x == 4) return puts("-1"), 0; else pos[x] = i; } } if (!fg) putchar('0'), putchar(' '), print(d[Y]); else if (pos[0] && pos[1]) { if (sort(pos, pos + 4, cmp), d[pos[1]] == d[pos[2]]) for (y = pos[0]; y; y = fa[y]) if (y == pos[2]) break; else if (y == pos[1]) { swap(pos[1], pos[2]); break; } xi = pos[0], yi = pos[1]; int X1 = xi, Y1 = yi, now, f1 = 0, f2 = 0, tp; if (d[xi] > d[yi]) for (; d[xi] > d[yi]; c1[++t1] = a[xi], c3[++t3] = b[xi], vis[xi] = 1, xi = fa[xi]) ; else for (; d[yi] > d[xi]; c2[++t2] = a[yi], c4[++t4] = b[yi], vis[yi] = -1, yi = fa[yi]) ; for (; xi != yi; c1[++t1] = a[xi], c3[++t3] = b[xi], c2[++t2] = a[yi], c4[++t4] = b[yi], vis[xi] = 1, vis[yi] = -1, xi = fa[xi], yi = fa[yi]) ; if ((pos[2] && !vis[pos[2]]) || (pos[3] && !vis[pos[3]])) return puts("-1"), 0; if (a[xi] != b[xi]) c1[++t1] = a[xi], c3[++t3] = b[xi]; for (; t2; c1[++t1] = c2[t2--]) ; for (; t4; c3[++t3] = c4[t4--]) ; for (i = 1; i <= t3; i++) if (c3[i] == c1[1]) { for (f1 = i - 1, f2 = t1 - i + 1, now = i, i = 1; i <= t1 && c1[i] == c3[now]; now == t1 ? now = 1 : now++, i++) ; if (i <= t1) return puts("-1"), 0; break; } if (xi == X1) prin(fa[xi], Y1), xi = fa[xi]; else if (xi == Y1) prin(fa[xi], X1), xi = fa[xi]; else prin(X1, Y1); for (; Y != X && !vis[Y]; fx++, Y = fa[Y]) ; switch (vis[Y]) { case 0: for (tp = 0; !u[xi]; xi = fa[xi], tp++) ; print(fx + (long long)(f1 > f2 ? f2 : f1) * (t1 + 1) + (tp << 1)); break; case 1: tmp = min((long long)f1 * (t1 + 1) - d[xi] + d[Y], (long long)f2 * (t1 + 1) - d[Y] + d[xi]), print(fx + d[xi] + tmp); break; case -1: tmp = min((long long)f1 * (t1 + 1) + d[xi] - d[Y], (long long)f2 * (t1 + 1) + d[Y] - d[xi]), print(fx + d[xi] + tmp); break; } } else puts("-1"); }
### Prompt Generate a cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int fx, vis[200002], c1[200002], c2[200002], c3[200002], c4[200002], t1, t2, t3, t4, xi, yi, pos[4], et = 1, e[200002], cd[200002 << 1], nt[200002 << 1], a[200002], b[200002], fa[200002], d[200002], n, wt, ss[19]; char fl[1 << 23], *A = fl; bool fg; bool u[200002]; void read(int& x) { char c; for (x = 0; '0' > (c = *A++) || c > '9';) ; while ('0' <= c && c <= '9') x = (x << 3) + (x << 1) + c - 48, (c = *A++); } void print(long long x) { if (!x) putchar(48); else { for (wt = 0; x; ss[++wt] = x % 10, x /= 10) ; for (; wt; putchar(ss[wt--] + 48)) ; } } void dfs(int x, int fe) { for (int y = e[x]; y; y = nt[y]) if (y != fe) fa[cd[y]] = x, d[cd[y]] = d[x] + 1, dfs(cd[y], y ^ 1); } void prin(int x, int y) { if (x < y) print(x), putchar(' '), print(y), putchar(' '); else print(y), putchar(' '), print(x), putchar(' '); } bool cmp(int x, int y) { return d[x] > d[y]; } long long min(long long a, long long b) { return a > b ? b : a; } int main() { int i, x, y, X, Y; long long tmp; for (*(fl + fread(fl, 1, 1 << 23, stdin)) = EOF, read(n), i = 1; i <= n; i++) if (read(a[i]), !a[i]) X = i; for (i = 1; i <= n; i++) if (read(b[i]), !b[i]) Y = i; for (i = 1; i < n; read(x), read(y), cd[++et] = y, nt[et] = e[x], e[x] = et, cd[++et] = x, nt[et] = e[y], e[y] = et, i++) ; for (dfs(X, 0), u[X] = true, y = Y; y != X; u[y] = true, swap(b[y], b[fa[y]]), y = fa[y]) ; for (i = 1; i <= n; i++) if (a[i] != b[i]) { int ti = 0; fg = true; for (y = e[i]; y && ti <= 1; y = nt[y]) if (a[cd[y]] != b[cd[y]]) ti++; if (ti <= 1) { for (x = 0; x < 4 && pos[x]; x++) ; if (x == 4) return puts("-1"), 0; else pos[x] = i; } } if (!fg) putchar('0'), putchar(' '), print(d[Y]); else if (pos[0] && pos[1]) { if (sort(pos, pos + 4, cmp), d[pos[1]] == d[pos[2]]) for (y = pos[0]; y; y = fa[y]) if (y == pos[2]) break; else if (y == pos[1]) { swap(pos[1], pos[2]); break; } xi = pos[0], yi = pos[1]; int X1 = xi, Y1 = yi, now, f1 = 0, f2 = 0, tp; if (d[xi] > d[yi]) for (; d[xi] > d[yi]; c1[++t1] = a[xi], c3[++t3] = b[xi], vis[xi] = 1, xi = fa[xi]) ; else for (; d[yi] > d[xi]; c2[++t2] = a[yi], c4[++t4] = b[yi], vis[yi] = -1, yi = fa[yi]) ; for (; xi != yi; c1[++t1] = a[xi], c3[++t3] = b[xi], c2[++t2] = a[yi], c4[++t4] = b[yi], vis[xi] = 1, vis[yi] = -1, xi = fa[xi], yi = fa[yi]) ; if ((pos[2] && !vis[pos[2]]) || (pos[3] && !vis[pos[3]])) return puts("-1"), 0; if (a[xi] != b[xi]) c1[++t1] = a[xi], c3[++t3] = b[xi]; for (; t2; c1[++t1] = c2[t2--]) ; for (; t4; c3[++t3] = c4[t4--]) ; for (i = 1; i <= t3; i++) if (c3[i] == c1[1]) { for (f1 = i - 1, f2 = t1 - i + 1, now = i, i = 1; i <= t1 && c1[i] == c3[now]; now == t1 ? now = 1 : now++, i++) ; if (i <= t1) return puts("-1"), 0; break; } if (xi == X1) prin(fa[xi], Y1), xi = fa[xi]; else if (xi == Y1) prin(fa[xi], X1), xi = fa[xi]; else prin(X1, Y1); for (; Y != X && !vis[Y]; fx++, Y = fa[Y]) ; switch (vis[Y]) { case 0: for (tp = 0; !u[xi]; xi = fa[xi], tp++) ; print(fx + (long long)(f1 > f2 ? f2 : f1) * (t1 + 1) + (tp << 1)); break; case 1: tmp = min((long long)f1 * (t1 + 1) - d[xi] + d[Y], (long long)f2 * (t1 + 1) - d[Y] + d[xi]), print(fx + d[xi] + tmp); break; case -1: tmp = min((long long)f1 * (t1 + 1) + d[xi] - d[Y], (long long)f2 * (t1 + 1) + d[Y] - d[xi]), print(fx + d[xi] + tmp); break; } } else puts("-1"); } ```
#include <bits/stdc++.h> using namespace std; inline void read(int &x) { int v = 0, f = 1; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = (c & 15); while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15); x = v * f; } inline void read(long long &x) { long long v = 0ll, f = 1ll; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = (c & 15); while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15); x = v * f; } inline void readc(char &x) { char c; while (((c = getchar()) == ' ') || c == '\n') ; x = c; } using namespace std; const int N = 200200; int n, tt, v, s, t, x, y, tx, ty, Q, L, p, fl; long long ans; int hd[N], fa[N], vi[N], d[N], a[N], b[N]; struct edge { int n, v; } e[N << 1]; void add(int tt, int v) { e[++fl] = {hd[tt], v}; hd[tt] = fl; } void dfs(int tt) { for (int i = hd[tt], v; v = e[i].v, i; i = e[i].n) if (v != fa[tt]) fa[v] = tt, d[v] = d[tt] + 1, dfs(v); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), s = a[i] ? s : i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), t = b[i] ? t : i; for (int i = 2; i <= n; i++) scanf("%d%d", &tt, &v), add(tt, v), add(v, tt); dfs(t); ans = d[s]; for (tt = s; tt; tt = fa[tt]) a[tt] = a[fa[tt]]; vector<int> v; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[x] < d[i]) x = i; tx = x; for (; a[x] != b[x]; x = fa[x]) { vi[x] = 1; v.push_back(x); } if (!tx) return cout << 0 << ' ' << ans << '\n', 0; reverse((v).begin(), (v).end()); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[y] < d[i]) y = i; ty = y ? y : x; for (; a[y] != b[y]; y = fa[y]) { vi[y] = 1; v.push_back(y); } if (y && x != y) return puts("-1"), 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i]) return puts("-1"), 0; for (int i = 1; i <= n; i++) vi[i] = 0; for (tt = s; tt; tt = fa[tt]) vi[tt] = 1; if (!vi[v[0]]) reverse((v).begin(), (v).end()); for (int i = 0; i <= v.size() - 1; i++) if (a[v[0]] == b[v[i]]) p = i; for (int i = 0; i <= v.size() - 1; i++) if (a[v[i]] != b[v[(i + p) % v.size()]]) return puts("-1"), 0; for (int i = 0; i <= v.size() - 1; i++) if (!vi[v[i]]) { L = i; break; } ans += min(1ll * (v.size() + 1) * p, 1ll * (v.size() + 1) * (v.size() - p) - 2 * L); for (; !vi[x]; x = fa[x]) ans += 2; if (tx > ty) swap(tx, ty); cout << tx << ' ' << ty << ' ' << ans << '\n'; }
### Prompt Your task is to create a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline void read(int &x) { int v = 0, f = 1; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = (c & 15); while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15); x = v * f; } inline void read(long long &x) { long long v = 0ll, f = 1ll; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = (c & 15); while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15); x = v * f; } inline void readc(char &x) { char c; while (((c = getchar()) == ' ') || c == '\n') ; x = c; } using namespace std; const int N = 200200; int n, tt, v, s, t, x, y, tx, ty, Q, L, p, fl; long long ans; int hd[N], fa[N], vi[N], d[N], a[N], b[N]; struct edge { int n, v; } e[N << 1]; void add(int tt, int v) { e[++fl] = {hd[tt], v}; hd[tt] = fl; } void dfs(int tt) { for (int i = hd[tt], v; v = e[i].v, i; i = e[i].n) if (v != fa[tt]) fa[v] = tt, d[v] = d[tt] + 1, dfs(v); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), s = a[i] ? s : i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), t = b[i] ? t : i; for (int i = 2; i <= n; i++) scanf("%d%d", &tt, &v), add(tt, v), add(v, tt); dfs(t); ans = d[s]; for (tt = s; tt; tt = fa[tt]) a[tt] = a[fa[tt]]; vector<int> v; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[x] < d[i]) x = i; tx = x; for (; a[x] != b[x]; x = fa[x]) { vi[x] = 1; v.push_back(x); } if (!tx) return cout << 0 << ' ' << ans << '\n', 0; reverse((v).begin(), (v).end()); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[y] < d[i]) y = i; ty = y ? y : x; for (; a[y] != b[y]; y = fa[y]) { vi[y] = 1; v.push_back(y); } if (y && x != y) return puts("-1"), 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i]) return puts("-1"), 0; for (int i = 1; i <= n; i++) vi[i] = 0; for (tt = s; tt; tt = fa[tt]) vi[tt] = 1; if (!vi[v[0]]) reverse((v).begin(), (v).end()); for (int i = 0; i <= v.size() - 1; i++) if (a[v[0]] == b[v[i]]) p = i; for (int i = 0; i <= v.size() - 1; i++) if (a[v[i]] != b[v[(i + p) % v.size()]]) return puts("-1"), 0; for (int i = 0; i <= v.size() - 1; i++) if (!vi[v[i]]) { L = i; break; } ans += min(1ll * (v.size() + 1) * p, 1ll * (v.size() + 1) * (v.size() - p) - 2 * L); for (; !vi[x]; x = fa[x]) ans += 2; if (tx > ty) swap(tx, ty); cout << tx << ' ' << ty << ' ' << ans << '\n'; } ```
#include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 7; const long long INF = 1e9 + 7; long long a[N], b[N], c[N], fc[N], pos[N], fa[N], dep[N], sz[N], dg[N], id[N], p[N], bp[N], cp[N]; bool g[N]; long long n, r1, r2, num = 0; struct edge { long long v, next; } e[N * 2]; void add(long long x, long long y) { e[num] = (edge){y, pos[x]}; pos[x] = num++; } void dfs(long long x, long long f, long long d) { dep[x] = d; fa[x] = f; if (x == r2) sz[x] = 1; else sz[x] = 0; for (long long i = pos[x]; ~i; i = e[i].next) { if (e[i].v == f) continue; dfs(e[i].v, x, d + 1); sz[x] += sz[e[i].v]; } } void dfs2(long long x, long long d, long long f) { id[x] = d; p[d] = x; for (long long i = pos[x]; ~i; i = e[i].next) { if (!g[e[i].v] || e[i].v == f) continue; dfs2(e[i].v, d + 1, x); } } long long fd(long long x, long long &xx, long long f) { if (g[x]) { xx = id[x]; return 0; } for (long long i = pos[x]; ~i; i = e[i].next) { if (e[i].v == f) continue; long long t = fd(e[i].v, xx, x); if (~t) return t + 1; } return -1; } int main() { scanf("%lld", &n); for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]); for (long long i = 1; i <= n; i++) scanf("%lld", &b[i]); for (long long i = 1; i <= n; i++) { if (!a[i]) r1 = i; if (!b[i]) r2 = i; } memset(pos, -1, sizeof(pos)); for (long long i = 1; i <= n - 1; i++) { long long x, y; scanf("%lld%lld", &x, &y); add(x, y); add(y, x); } dfs(r1, 0, 1); for (long long i = 1; i <= n; i++) { if (sz[i] && i != r1) c[fa[i]] = a[i]; if (i == r2) c[i] = 0; if (!sz[i]) c[i] = a[i]; } bool fl = 0; for (long long i = 1; i <= n; i++) { if (c[i] != b[i]) { fl = 1; break; } } if (!fl) { printf("0 %lld\n", dep[r2] - 1); return 0; } for (long long i = 1; i <= n; i++) fc[c[i]] = i; long long mn = INF, md; for (long long i = 1; i <= n; i++) { if (b[fc[a[i]]] != a[i]) { g[i] = 1; if (dep[i] < mn) { mn = dep[i]; md = i; } } } g[fa[md]] = 1; for (long long i = 1; i <= n; i++) { dg[i] = 0; for (long long j = pos[i]; ~j; j = e[j].next) dg[i] += g[e[j].v]; } long long t1 = 0, t2 = 0, sg = 0; for (long long i = 1; i <= n; i++) { if (!g[i]) continue; sg++; if (dg[i] < 1 || dg[i] > 2) { puts("-1"); return 0; } if (dg[i] == 1) { if (!t1) t1 = i; else if (!t2) t2 = i; else { puts("-1"); return 0; } } } dfs2(t1, 1, 0); long long v1, v2, np = 0; long long ans = fd(r1, v1, 0) + fd(r2, v2, 0); for (long long i = 1; i <= sg; i++) if (i != v2) p[++np] = p[i]; for (long long i = 1; i <= sg - 1; i++) bp[i] = b[p[i]], cp[i] = c[p[i]]; long long rw = -1; for (long long i = 0; i <= sg - 1 - 1; i++) if (bp[1] == cp[i + 1]) rw = i; if (rw < 0) { puts("-1"); return 0; } for (long long i = 1; i <= sg - 1; i++) if (bp[i] != cp[(i - 1 + rw) % (sg - 1) + 1]) { puts("-1"); return 0; } long long tt; if (v1 == v2) tt = sg * min(rw, (sg - 1) - rw); else if (v1 < v2) tt = min(sg * rw + (v2 - v1), sg * (sg - 1 - rw) - (v2 - v1)); else tt = min(sg * rw - (v1 - v2), sg * (sg - 1 - rw) + (v1 - v2)); printf("%lld %lld %lld\n", min(t1, t2), max(t1, t2), tt + ans); return 0; }
### Prompt Create a solution in CPP for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 7; const long long INF = 1e9 + 7; long long a[N], b[N], c[N], fc[N], pos[N], fa[N], dep[N], sz[N], dg[N], id[N], p[N], bp[N], cp[N]; bool g[N]; long long n, r1, r2, num = 0; struct edge { long long v, next; } e[N * 2]; void add(long long x, long long y) { e[num] = (edge){y, pos[x]}; pos[x] = num++; } void dfs(long long x, long long f, long long d) { dep[x] = d; fa[x] = f; if (x == r2) sz[x] = 1; else sz[x] = 0; for (long long i = pos[x]; ~i; i = e[i].next) { if (e[i].v == f) continue; dfs(e[i].v, x, d + 1); sz[x] += sz[e[i].v]; } } void dfs2(long long x, long long d, long long f) { id[x] = d; p[d] = x; for (long long i = pos[x]; ~i; i = e[i].next) { if (!g[e[i].v] || e[i].v == f) continue; dfs2(e[i].v, d + 1, x); } } long long fd(long long x, long long &xx, long long f) { if (g[x]) { xx = id[x]; return 0; } for (long long i = pos[x]; ~i; i = e[i].next) { if (e[i].v == f) continue; long long t = fd(e[i].v, xx, x); if (~t) return t + 1; } return -1; } int main() { scanf("%lld", &n); for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]); for (long long i = 1; i <= n; i++) scanf("%lld", &b[i]); for (long long i = 1; i <= n; i++) { if (!a[i]) r1 = i; if (!b[i]) r2 = i; } memset(pos, -1, sizeof(pos)); for (long long i = 1; i <= n - 1; i++) { long long x, y; scanf("%lld%lld", &x, &y); add(x, y); add(y, x); } dfs(r1, 0, 1); for (long long i = 1; i <= n; i++) { if (sz[i] && i != r1) c[fa[i]] = a[i]; if (i == r2) c[i] = 0; if (!sz[i]) c[i] = a[i]; } bool fl = 0; for (long long i = 1; i <= n; i++) { if (c[i] != b[i]) { fl = 1; break; } } if (!fl) { printf("0 %lld\n", dep[r2] - 1); return 0; } for (long long i = 1; i <= n; i++) fc[c[i]] = i; long long mn = INF, md; for (long long i = 1; i <= n; i++) { if (b[fc[a[i]]] != a[i]) { g[i] = 1; if (dep[i] < mn) { mn = dep[i]; md = i; } } } g[fa[md]] = 1; for (long long i = 1; i <= n; i++) { dg[i] = 0; for (long long j = pos[i]; ~j; j = e[j].next) dg[i] += g[e[j].v]; } long long t1 = 0, t2 = 0, sg = 0; for (long long i = 1; i <= n; i++) { if (!g[i]) continue; sg++; if (dg[i] < 1 || dg[i] > 2) { puts("-1"); return 0; } if (dg[i] == 1) { if (!t1) t1 = i; else if (!t2) t2 = i; else { puts("-1"); return 0; } } } dfs2(t1, 1, 0); long long v1, v2, np = 0; long long ans = fd(r1, v1, 0) + fd(r2, v2, 0); for (long long i = 1; i <= sg; i++) if (i != v2) p[++np] = p[i]; for (long long i = 1; i <= sg - 1; i++) bp[i] = b[p[i]], cp[i] = c[p[i]]; long long rw = -1; for (long long i = 0; i <= sg - 1 - 1; i++) if (bp[1] == cp[i + 1]) rw = i; if (rw < 0) { puts("-1"); return 0; } for (long long i = 1; i <= sg - 1; i++) if (bp[i] != cp[(i - 1 + rw) % (sg - 1) + 1]) { puts("-1"); return 0; } long long tt; if (v1 == v2) tt = sg * min(rw, (sg - 1) - rw); else if (v1 < v2) tt = min(sg * rw + (v2 - v1), sg * (sg - 1 - rw) - (v2 - v1)); else tt = min(sg * rw - (v1 - v2), sg * (sg - 1 - rw) + (v1 - v2)); printf("%lld %lld %lld\n", min(t1, t2), max(t1, t2), tt + ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; int v1[200500], v2[200500], v3[200500], s, t, head[200500], cnt, is[200500], fr[200500], ct, st[200500], fg, s1, s2, s3, s4, s5, a, b, st2[200500], ct2, vl[200500], c1, ins[200500], n, fr2[200500], is2[200500], d1, is3[200500]; struct edge { int t, next; } ed[200500 * 2]; void adde(int f, int t) { ed[++cnt] = (edge){t, head[f]}; head[f] = cnt; ed[++cnt] = (edge){f, head[t]}; head[t] = cnt; } void dfs(int u, int fa) { if (!fg) st[++ct] = u; if (u == t) fg = 1; for (int i = head[u]; i; i = ed[i].next) if (ed[i].t != fa) dfs(ed[i].t, u); if (!fg) ct--; } bool check(int l, int r) { t = r; ct = 0; fg = 0; dfs(l, 0); for (int i = 1; i <= n; i++) ins[i] = 0; for (int i = 1; i <= ct; i++) ins[st[i]] = 1; for (int i = 1; i <= n; i++) if (is[i] && !ins[i]) return 0; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &v1[i]); if (!v1[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &v2[i]); if (!v2[i]) t = i; } for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), adde(a, b); dfs(s, 0); s3 = s, s4 = t; for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; int fg1 = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { fg1 = 1; is[i] = 1; for (int j = head[i]; j; j = ed[j].next) fr[ed[j].t]++; } if (!fg1) { printf("0 %d\n", ct - 1); return 0; } for (int i = 1; i <= n; i++) if (is[i] && fr[i] <= 1) vl[++c1] = i; if (c1 > 4) { printf("-1\n"); return 0; } for (int i = 1; i <= c1 && fg1 == 1; i++) for (int j = i + 1; j <= c1; j++) if (check(vl[i], vl[j])) { s1 = vl[i], s2 = vl[j]; fg1 = 2; break; } t = s2; ct = fg = 0; dfs(s1, 0); for (int i = 1; i <= ct; i++) is3[st[i]] = 1; if (fg1 == 1) { printf("-1\n"); return 0; } int v4 = 0; for (int i = 1; i <= ct; i++) if (!is[st[i]]) { if (v4) { printf("-1\n"); return 0; } v4 = st[i]; } if (!v4) { t = s1; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s1 = v4; else { t = s2; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s2 = v4; else { int st = 1; for (int i = head[s]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st = 2; if (s1 == s) s1 = v4; else s2 = v4; } if (st == 1) { int st2 = 0, st3 = (s1 == s ? s2 : s1); for (int i = head[st3]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st2 = 1; if (s1 == s) s2 = v4; else s1 = v4; } if (!st2) { printf("-1\n"); return 0; } } } } } else { t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= ct; i++) if (is3[st[i]]) { v4 = st[i]; break; } } t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; long long as = ct - 1; t = s2; ct = 0; fg = 0; dfs(s1, 0); int ct1 = 0, ct2 = 0, fg2 = -1, tp = 0; for (int i = 1; i <= ct; i++) fr2[v2[st[i]]] = i, is2[st[i]] = 1; for (int i = 1; i <= ct; i++) { if (!v3[st[i]]) continue; int nt = fr2[v3[st[i]]]; fr2[v3[st[i]]] = 0; if (!nt) { printf("-1\n"); return 0; } int st = i - nt + (i < nt ? ct : 0); if (fg2 == -1) fg2 = st, ct1 = 1; else { if (fg2 == st) ct1++; else if (fg2 == st - 1) ct2++; else if (fg2 == st + 1) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1; ct1 = 1, fg2--; } else if (fg2 == 0 && st + 1 == ct) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1, ct1 = 1, fg2 = ct - 1; } else if (st == 0 && fg2 == ct - 1) ct2++; else { printf("-1\n"); return 0; } } } for (int i = 1; i <= ct; i++) v3[st[i]] = v2[st[i]]; long long as1 = 1ll * ct1 * fg2 + 1ll * ct2 * (fg2 + 1), as2 = 1ll * ct1 * (ct - fg2) + 1ll * ct2 * (ct - fg2 - 1); if (as2 < as1) as1 = as2; as += as1; for (int i = 1; i <= n; i++) if (fr2[v2[i]]) s5 = i; v3[s5] = 0; t = s4; ct = 0; fg = 0; dfs(s5, 0); for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { printf("-1\n"); if (d1) printf("%d\n", i); return 0; } as += ct - 1; if (s1 > s2) s1 ^= s2 ^= s1 ^= s2; printf("%d %d %lld\n", s1, s2, as); }
### Prompt Construct a CPP code solution to the problem outlined: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int v1[200500], v2[200500], v3[200500], s, t, head[200500], cnt, is[200500], fr[200500], ct, st[200500], fg, s1, s2, s3, s4, s5, a, b, st2[200500], ct2, vl[200500], c1, ins[200500], n, fr2[200500], is2[200500], d1, is3[200500]; struct edge { int t, next; } ed[200500 * 2]; void adde(int f, int t) { ed[++cnt] = (edge){t, head[f]}; head[f] = cnt; ed[++cnt] = (edge){f, head[t]}; head[t] = cnt; } void dfs(int u, int fa) { if (!fg) st[++ct] = u; if (u == t) fg = 1; for (int i = head[u]; i; i = ed[i].next) if (ed[i].t != fa) dfs(ed[i].t, u); if (!fg) ct--; } bool check(int l, int r) { t = r; ct = 0; fg = 0; dfs(l, 0); for (int i = 1; i <= n; i++) ins[i] = 0; for (int i = 1; i <= ct; i++) ins[st[i]] = 1; for (int i = 1; i <= n; i++) if (is[i] && !ins[i]) return 0; return 1; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &v1[i]); if (!v1[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &v2[i]); if (!v2[i]) t = i; } for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), adde(a, b); dfs(s, 0); s3 = s, s4 = t; for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; int fg1 = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { fg1 = 1; is[i] = 1; for (int j = head[i]; j; j = ed[j].next) fr[ed[j].t]++; } if (!fg1) { printf("0 %d\n", ct - 1); return 0; } for (int i = 1; i <= n; i++) if (is[i] && fr[i] <= 1) vl[++c1] = i; if (c1 > 4) { printf("-1\n"); return 0; } for (int i = 1; i <= c1 && fg1 == 1; i++) for (int j = i + 1; j <= c1; j++) if (check(vl[i], vl[j])) { s1 = vl[i], s2 = vl[j]; fg1 = 2; break; } t = s2; ct = fg = 0; dfs(s1, 0); for (int i = 1; i <= ct; i++) is3[st[i]] = 1; if (fg1 == 1) { printf("-1\n"); return 0; } int v4 = 0; for (int i = 1; i <= ct; i++) if (!is[st[i]]) { if (v4) { printf("-1\n"); return 0; } v4 = st[i]; } if (!v4) { t = s1; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s1 = v4; else { t = s2; ct = fg = 0; dfs(s, 0); if (ct > 1 && !is[st[ct - 1]]) v4 = st[ct - 1], s2 = v4; else { int st = 1; for (int i = head[s]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st = 2; if (s1 == s) s1 = v4; else s2 = v4; } if (st == 1) { int st2 = 0, st3 = (s1 == s ? s2 : s1); for (int i = head[st3]; i; i = ed[i].next) if (!is[ed[i].t]) { v4 = ed[i].t, st2 = 1; if (s1 == s) s2 = v4; else s1 = v4; } if (!st2) { printf("-1\n"); return 0; } } } } } else { t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= ct; i++) if (is3[st[i]]) { v4 = st[i]; break; } } t = v4; ct = 0; fg = 0; dfs(s, 0); for (int i = 1; i <= n; i++) v3[i] = v1[i]; for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; long long as = ct - 1; t = s2; ct = 0; fg = 0; dfs(s1, 0); int ct1 = 0, ct2 = 0, fg2 = -1, tp = 0; for (int i = 1; i <= ct; i++) fr2[v2[st[i]]] = i, is2[st[i]] = 1; for (int i = 1; i <= ct; i++) { if (!v3[st[i]]) continue; int nt = fr2[v3[st[i]]]; fr2[v3[st[i]]] = 0; if (!nt) { printf("-1\n"); return 0; } int st = i - nt + (i < nt ? ct : 0); if (fg2 == -1) fg2 = st, ct1 = 1; else { if (fg2 == st) ct1++; else if (fg2 == st - 1) ct2++; else if (fg2 == st + 1) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1; ct1 = 1, fg2--; } else if (fg2 == 0 && st + 1 == ct) { if (ct2) { printf("-1\n"); return 0; } ct2 = ct1, ct1 = 1, fg2 = ct - 1; } else if (st == 0 && fg2 == ct - 1) ct2++; else { printf("-1\n"); return 0; } } } for (int i = 1; i <= ct; i++) v3[st[i]] = v2[st[i]]; long long as1 = 1ll * ct1 * fg2 + 1ll * ct2 * (fg2 + 1), as2 = 1ll * ct1 * (ct - fg2) + 1ll * ct2 * (ct - fg2 - 1); if (as2 < as1) as1 = as2; as += as1; for (int i = 1; i <= n; i++) if (fr2[v2[i]]) s5 = i; v3[s5] = 0; t = s4; ct = 0; fg = 0; dfs(s5, 0); for (int i = 1; i < ct; i++) v3[st[i]] = v3[st[i + 1]]; v3[st[ct]] = 0; for (int i = 1; i <= n; i++) if (v2[i] != v3[i]) { printf("-1\n"); if (d1) printf("%d\n", i); return 0; } as += ct - 1; if (s1 > s2) s1 ^= s2 ^= s1 ^= s2; printf("%d %d %lld\n", s1, s2, as); } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 7; int n, s, t, p, x, y, last[maxn], a[maxn], b[maxn], r[maxn], d[maxn]; vector<int> g, h, A, B; pair<int, int> P = {maxn, 0}; struct Edge { int v, nxt; } e[2 * maxn]; int read() { int x = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + (c ^ 48), c = getchar(); return x; } inline void add(int u, int v) { static int cnt = 0; e[++cnt] = {v, last[u]}, last[u] = cnt; } bool dfs1(int u, int fa) { g.push_back(u); if (u == t) return 1; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (dfs1(v, u)) return 1; } g.pop_back(); return 0; } void dfs2(int u, int fa, int d) { if (a[u] != b[u]) { h.push_back(u), r[u] = 1; if (d - 1 == P.first && fa != P.second) printf("-1\n"), exit(0); ; if (d - 1 < P.first) P = {d - 1, fa}; } for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs2(v, u, d + 1); } } void dfs3(int u, int fa) { if (u != p) A.push_back(a[u]), B.push_back(b[u]); for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (r[v]) dfs3(v, u); } } int dfs4(int u, int fa, int d, int t) { if (u == t) return d; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; int ret = dfs4(v, u, d + 1, t); if (ret) return ret; } return 0; } int calc(vector<int> A, vector<int> B) { int pos = 0, siz = A.size(); for (int i = 0; i < B.size(); i++) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (int i = 0; i < A.size(); i++) if (A[i] != B[(i + pos) % siz]) return 0; return pos; } inline int S(int x, int y) { return dfs4(x, 0, 0, y); } inline long long get(int x, int y) { int c = calc(A, B); return S(s, x) + 1ll * (c - 1) * (A.size() + 1) + S(y, t) + 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), s = a[i] ? s : i; for (int i = 1; i <= n; i++) b[i] = read(), t = b[i] ? t : i; for (int i = 1; i < n; i++) { x = read(), y = read(); add(x, y), add(y, x); } dfs1(s, 0); for (int i = 1; i < g.size(); i++) swap(a[g[i - 1]], a[g[i]]); bool flag = 1; for (int i = 1; i <= n; i++) flag &= a[i] == b[i]; if (flag) { printf("0 %d\n", g.size() - 1); return 0; } dfs2(t, 0, 0); h.push_back(p = P.second); r[p] = 1; for (int i = 0; i < h.size(); i++) { int u = h[i]; for (int j = last[u]; j; j = e[j].nxt) { int v = e[j].v; if (r[v]) d[u]++; } } vector<int> c; for (int i = 0; i < h.size(); i++) { int u = h[i]; if (d[u] == 1) c.push_back(u); else if (d[u] != 2) printf("-1\n"), exit(0); ; } if (c.size() != 2) printf("-1\n"), exit(0); ; if (c[0] > c[1]) swap(c[0], c[1]); dfs3(c[0], 0); if (!calc(A, B)) printf("-1\n"), exit(0); ; printf("%d %d ", c[0], c[1]); long long ans = get(c[0], c[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); ans = min(ans, get(c[1], c[0])); printf("%lld\n", ans); return 0; }
### Prompt Your task is to create a CPP solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 7; int n, s, t, p, x, y, last[maxn], a[maxn], b[maxn], r[maxn], d[maxn]; vector<int> g, h, A, B; pair<int, int> P = {maxn, 0}; struct Edge { int v, nxt; } e[2 * maxn]; int read() { int x = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + (c ^ 48), c = getchar(); return x; } inline void add(int u, int v) { static int cnt = 0; e[++cnt] = {v, last[u]}, last[u] = cnt; } bool dfs1(int u, int fa) { g.push_back(u); if (u == t) return 1; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (dfs1(v, u)) return 1; } g.pop_back(); return 0; } void dfs2(int u, int fa, int d) { if (a[u] != b[u]) { h.push_back(u), r[u] = 1; if (d - 1 == P.first && fa != P.second) printf("-1\n"), exit(0); ; if (d - 1 < P.first) P = {d - 1, fa}; } for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs2(v, u, d + 1); } } void dfs3(int u, int fa) { if (u != p) A.push_back(a[u]), B.push_back(b[u]); for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (r[v]) dfs3(v, u); } } int dfs4(int u, int fa, int d, int t) { if (u == t) return d; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; int ret = dfs4(v, u, d + 1, t); if (ret) return ret; } return 0; } int calc(vector<int> A, vector<int> B) { int pos = 0, siz = A.size(); for (int i = 0; i < B.size(); i++) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (int i = 0; i < A.size(); i++) if (A[i] != B[(i + pos) % siz]) return 0; return pos; } inline int S(int x, int y) { return dfs4(x, 0, 0, y); } inline long long get(int x, int y) { int c = calc(A, B); return S(s, x) + 1ll * (c - 1) * (A.size() + 1) + S(y, t) + 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), s = a[i] ? s : i; for (int i = 1; i <= n; i++) b[i] = read(), t = b[i] ? t : i; for (int i = 1; i < n; i++) { x = read(), y = read(); add(x, y), add(y, x); } dfs1(s, 0); for (int i = 1; i < g.size(); i++) swap(a[g[i - 1]], a[g[i]]); bool flag = 1; for (int i = 1; i <= n; i++) flag &= a[i] == b[i]; if (flag) { printf("0 %d\n", g.size() - 1); return 0; } dfs2(t, 0, 0); h.push_back(p = P.second); r[p] = 1; for (int i = 0; i < h.size(); i++) { int u = h[i]; for (int j = last[u]; j; j = e[j].nxt) { int v = e[j].v; if (r[v]) d[u]++; } } vector<int> c; for (int i = 0; i < h.size(); i++) { int u = h[i]; if (d[u] == 1) c.push_back(u); else if (d[u] != 2) printf("-1\n"), exit(0); ; } if (c.size() != 2) printf("-1\n"), exit(0); ; if (c[0] > c[1]) swap(c[0], c[1]); dfs3(c[0], 0); if (!calc(A, B)) printf("-1\n"), exit(0); ; printf("%d %d ", c[0], c[1]); long long ans = get(c[0], c[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); ans = min(ans, get(c[1], c[0])); printf("%lld\n", ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; int n, S, T, a[200050], b[200050], anc[200050], dep[200050], head[200050]; bool in[200050]; bool mark[200050]; vector<int> v; struct edge { int to, nex; edge(int to = 0, int nex = 0) : to(to), nex(nex) {} }; vector<edge> G; void addedge(int u, int v) { G.push_back(edge(v, head[u])), head[u] = G.size() - 1; G.push_back(edge(u, head[v])), head[v] = G.size() - 1; } void dfs(int u) { for (int i = head[u]; ~i; i = G[i].nex) { int v = G[i].to; if (v != anc[u]) { anc[v] = u; dep[v] = dep[u] + 1; dfs(v); } } } bool solve() { dfs(T); for (int u = S;; u = anc[u]) { mark[u] = 1; if (u == T) { break; } else { swap(a[u], a[anc[u]]); } } int s1 = -1, p = -1; int s2 = -1, q = -1; for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (s1 == -1 || dep[s1] < dep[i]) { s1 = i; } } if (s1 == -1) { printf("0 %d\n", dep[S]); return true; } for (p = s1; a[p] != b[p]; p = anc[p]) { v.push_back(p); in[p] = 1; } int m = v.size(); for (int i = 1; i <= n; ++i) if (!in[i] && a[i] != b[i]) { if (s2 == -1 || dep[s2] < dep[i]) { s2 = i; } } if (s2 != -1) { for (q = s2; a[q] != b[q]; q = anc[q]) { if (in[q]) { return false; } v.push_back(q); in[q] = 1; } if (p != q) { return false; } reverse(v.begin() + m, v.end()); } else { s2 = p; } for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (!in[i]) { return false; } } int M = v.size(); int d = -1; for (int i = 1; i < M; ++i) { if (b[v[i]] == a[v[0]]) { d = i; break; } } assert(d != -1); for (int i = 0; i < M; ++i) { if (a[v[i]] != b[v[(i + d) % M]]) { return false; } } printf("%d %d ", min(s1, s2), max(s1, s2)); int cnt = 0; for (int i = 0; i < M; ++i) { if (mark[v[i]]) { ++cnt; } } long long an = dep[S]; if (cnt == 0) { an += (long long)min(d, M - d) * (M + 1); while (!mark[p]) { an += 2; p = anc[p]; } } else { for (int i = m; i < M; ++i) { if (mark[v[i]]) { d = M - d; break; } } an += min((long long)d * (M + 1) - (cnt << 1), (long long)(M - d) * (M + 1)); } printf("%I64d\n", an); return true; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (a[i] == 0) { S = i; } } for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (b[i] == 0) { T = i; } } memset(head, -1, sizeof(head)); for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); addedge(u, v); } if (!solve()) { printf("-1\n"); } return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n, S, T, a[200050], b[200050], anc[200050], dep[200050], head[200050]; bool in[200050]; bool mark[200050]; vector<int> v; struct edge { int to, nex; edge(int to = 0, int nex = 0) : to(to), nex(nex) {} }; vector<edge> G; void addedge(int u, int v) { G.push_back(edge(v, head[u])), head[u] = G.size() - 1; G.push_back(edge(u, head[v])), head[v] = G.size() - 1; } void dfs(int u) { for (int i = head[u]; ~i; i = G[i].nex) { int v = G[i].to; if (v != anc[u]) { anc[v] = u; dep[v] = dep[u] + 1; dfs(v); } } } bool solve() { dfs(T); for (int u = S;; u = anc[u]) { mark[u] = 1; if (u == T) { break; } else { swap(a[u], a[anc[u]]); } } int s1 = -1, p = -1; int s2 = -1, q = -1; for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (s1 == -1 || dep[s1] < dep[i]) { s1 = i; } } if (s1 == -1) { printf("0 %d\n", dep[S]); return true; } for (p = s1; a[p] != b[p]; p = anc[p]) { v.push_back(p); in[p] = 1; } int m = v.size(); for (int i = 1; i <= n; ++i) if (!in[i] && a[i] != b[i]) { if (s2 == -1 || dep[s2] < dep[i]) { s2 = i; } } if (s2 != -1) { for (q = s2; a[q] != b[q]; q = anc[q]) { if (in[q]) { return false; } v.push_back(q); in[q] = 1; } if (p != q) { return false; } reverse(v.begin() + m, v.end()); } else { s2 = p; } for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (!in[i]) { return false; } } int M = v.size(); int d = -1; for (int i = 1; i < M; ++i) { if (b[v[i]] == a[v[0]]) { d = i; break; } } assert(d != -1); for (int i = 0; i < M; ++i) { if (a[v[i]] != b[v[(i + d) % M]]) { return false; } } printf("%d %d ", min(s1, s2), max(s1, s2)); int cnt = 0; for (int i = 0; i < M; ++i) { if (mark[v[i]]) { ++cnt; } } long long an = dep[S]; if (cnt == 0) { an += (long long)min(d, M - d) * (M + 1); while (!mark[p]) { an += 2; p = anc[p]; } } else { for (int i = m; i < M; ++i) { if (mark[v[i]]) { d = M - d; break; } } an += min((long long)d * (M + 1) - (cnt << 1), (long long)(M - d) * (M + 1)); } printf("%I64d\n", an); return true; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (a[i] == 0) { S = i; } } for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (b[i] == 0) { T = i; } } memset(head, -1, sizeof(head)); for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); addedge(u, v); } if (!solve()) { printf("-1\n"); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 4e5 + 10; int w[N], ne[N], la[N]; int a[N], b[N], r, n, t, sw[N], fa[N], q, s1[N], dep[N], nx[N], s2[N]; void link(int x, int y) { w[++t] = y; ne[t] = la[x]; la[x] = t; } void dfs(int x) { for (int y = la[x]; y; y = ne[y]) { int z = w[y]; if (z == fa[x]) continue; fa[z] = x; dep[z] = dep[x] + 1; dfs(z); } } void go(int x) { if (x == r) return; if (fa[x] != r) go(fa[x]); swap(a[fa[x]], a[x]), sw[x] = 1; nx[fa[x]] = x; } int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%d", &a[i]), r = a[i] ? r : i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), q = b[i] ? q : i; int tag1 = 0; if (n == 200000 && a[1] == 13809) { tag1 = 0; } for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); link(x, y); link(y, x); } dfs(r); long long ans = dep[q]; go(q); sw[r] = 1; int case0 = 0; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && sw[i]) { case0 = 1; } } if (case0) { int cnt1 = 0, cnt2 = 0; for (int x = 1; x <= n; x++) { int cnt = 0; if (a[x] != b[x]) { for (int y = la[x]; y; y = ne[y]) cnt += a[w[y]] != b[w[y]]; if (cnt > 2) { cout << -1 << endl; return 0; } if (cnt == 1) cnt1++; s1[x] = cnt; s2[x] = cnt - (a[fa[x]] != b[fa[x]]); if (cnt == 0) cnt1 += 2; } else { if (sw[x] && b[x]) { for (int y = la[x]; y; y = ne[y]) cnt += a[w[y]] != b[w[y]]; if (cnt == 2 && a[fa[x]] != b[fa[x]]) { cnt2++; s1[x] = 100; for (int y = la[x]; y; y = ne[y]) { int z = w[y]; if (z != fa[x] && a[z] != b[z] && sw[z]) { cnt2 = 100; } } } } } } if (cnt1 == 2 && cnt2 == 0) { int x, y, z, X, Y, l = 0; for (int i = 1; i <= n; i++) { if (s1[i] == 1) y = x, x = i; if (a[i] != b[i] && (l == 0 || dep[i] < dep[l])) l = i; } if (sw[x] && sw[y]) { if (dep[x] > dep[y]) swap(x, y); X = x, z = Y = nx[y]; vector<int> a0; while (y != x) a0.push_back(y), y = fa[y]; a0.push_back(x); reverse(a0.begin(), a0.end()); int sum = 0, sum2 = 0; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k, ans2 = (a0.size() + 1) * (a0.size() - k) - 2 * sum; if (tag1) { cout << ans1 << ' ' << ans2 << ' ' << sum << endl; } if (tag1) { cout << 1 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } if (sw[x] + sw[y] == 1) { if (sw[x]) swap(x, y); X = x, Y = nx[y]; vector<int> a1, a2, a0; for (; x != l; x = fa[x]) a1.push_back(x); a1.push_back(l); for (; y != l; y = fa[y]) a2.push_back(y); a0 = a1; while (a2.size()) a0.push_back(a2.back()), a2.pop_back(); int sum = 0, sum2 = 0; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k, ans2 = (a0.size() + 1) * (a0.size() - k) - 2 * sum; if (tag1) { cout << ans1 << ' ' << ans2 << ' ' << sum << endl; } if (tag1) { cout << 2 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } cout << -1 << endl; return 0; } if (cnt1 == 4 && cnt2 == 1) { int x, y, u, X, Y, l = 0; for (int i = 1; i <= n; i++) if (s1[i] == 100) u = i; for (int i = 1; i <= n; i++) { if (s1[i] == 1 && s2[i] == 0 && !sw[i]) y = x, x = i; if (a[i] != b[i] && (l == 0 || dep[i] < dep[l])) l = i; } if (fa[l] == u) { cout << -1 << endl; return 0; } static int tag0[N]; X = x, Y = y; assert(sw[l]); assert(a[l] != b[l]); int x0 = x, y0 = y; while (x0 != l && x0 != u) { assert(a[x0] != b[x0]); assert(sw[x0] == 0); tag0[x0] = 1; x0 = fa[x0]; } while (y0 != l && y0 != u) { assert(a[y0] != b[y0]); assert(sw[y0] == 0); tag0[y0] = 1; y0 = fa[y0]; } assert(x0 != y0); int u0 = fa[u]; assert(sw[u] && a[u] == b[u]); while (u0 != l) { assert(sw[u0]); assert(a[u0] != b[u0]); tag0[u0] = 1; u0 = fa[u0]; } tag0[l] = 1; for (int i = 1; i <= n; i++) { if (tag0[i] != (a[i] != b[i])) { cout << -1 << endl; return 0; } assert(tag0[i] == (a[i] != b[i])); } vector<int> a1, a2, a0; int tag = 0; for (; x != l; x = fa[x]) a1.push_back(x), tag |= 1 * (x == u); for (; y != l; y = fa[y]) a2.push_back(y), tag |= 2 * (y == u); if (tag == 1) swap(a1, a2); a0 = a1; a0.push_back(l); while (a2.size()) { if (a2.back() != u) a0.push_back(a2.back()); a2.pop_back(); } int sum = 0, sum2 = 0; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k, ans2 = (a0.size() + 1) * (a0.size() - k) - 2 * sum; if (tag1) { cout << ans1 << ' ' << ans2 << ' ' << sum << endl; } if (tag1) { cout << l << ' ' << u << ' ' << dep[l] << ' ' << dep[u] << ' ' << dep[X] << ' ' << dep[Y] << ' ' << sw[u] << ' ' << nx[u] << endl; cout << 3 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } cout << -1 << endl; return 0; } int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0, cnt5 = 0; for (int x = 1; x <= n; x++) { int cnt = 0; if (a[x] == b[x]) { for (int y = la[x]; y; y = ne[y]) if (fa[x] != w[y]) cnt += a[w[y]] != b[w[y]]; if (cnt == 2) cnt1++; if (cnt == 1) cnt3++; if (cnt > 2) cnt4++; } else { cnt5++; for (int y = la[x]; y; y = ne[y]) if (fa[x] != w[y]) cnt += a[w[y]] != b[w[y]]; if (cnt == 0) cnt2++; if (cnt > 1) cnt4++; } s1[x] = cnt; } if (!cnt5) { cout << 0 << ' ' << ans << endl; return 0; } if (cnt4) { cout << -1 << endl; return 0; } if (cnt1 == 1 && cnt2 == 2) { int x, y, u, v, X, Y, z; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && a[fa[i]] == b[fa[i]]) v = u, u = i; if (a[i] != b[i] && s1[i] == 0) y = x, x = i; } X = x, Y = y; z = fa[u]; assert(z == fa[v]); if (sw[v]) swap(u, v); vector<int> a1, a2, a0; for (; x != u && x != v; x = fa[x]) a1.push_back(x); a1.push_back(x); for (; y != u && y != v; y = fa[y]) a2.push_back(y); a2.push_back(y); if (a2.back() == u) swap(a1, a2); a0 = a1; while (a2.size()) a0.push_back(a2.back()), a2.pop_back(); int sum = 0, sum2 = 0; while (!sw[z] && z != r) sum2 += 2, z = fa[z]; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k - 2 * sum, ans2 = (a0.size() + 1) * (a0.size() - k); if (tag1) { cout << 4 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } if (cnt3 == 1 && cnt2 == 1) { int x, y, z, X, Y; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && a[fa[i]] == b[fa[i]]) x = i; if (a[i] != b[i] && s1[i] == 0) y = i; } X = fa[x]; Y = y; z = fa[x]; vector<int> a0; while (y != x) a0.push_back(y), y = fa[y]; a0.push_back(x); reverse(a0.begin(), a0.end()); int sum = 0, sum2 = 0; while (!sw[z] && z != r) sum2 += 2, z = fa[z]; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k - 2 * sum, ans2 = (a0.size() + 1) * (a0.size() - k); if (tag1) { cout << 5 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } cout << -1 << endl; }
### Prompt Your task is to create a CPP solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 4e5 + 10; int w[N], ne[N], la[N]; int a[N], b[N], r, n, t, sw[N], fa[N], q, s1[N], dep[N], nx[N], s2[N]; void link(int x, int y) { w[++t] = y; ne[t] = la[x]; la[x] = t; } void dfs(int x) { for (int y = la[x]; y; y = ne[y]) { int z = w[y]; if (z == fa[x]) continue; fa[z] = x; dep[z] = dep[x] + 1; dfs(z); } } void go(int x) { if (x == r) return; if (fa[x] != r) go(fa[x]); swap(a[fa[x]], a[x]), sw[x] = 1; nx[fa[x]] = x; } int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%d", &a[i]), r = a[i] ? r : i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), q = b[i] ? q : i; int tag1 = 0; if (n == 200000 && a[1] == 13809) { tag1 = 0; } for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); link(x, y); link(y, x); } dfs(r); long long ans = dep[q]; go(q); sw[r] = 1; int case0 = 0; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && sw[i]) { case0 = 1; } } if (case0) { int cnt1 = 0, cnt2 = 0; for (int x = 1; x <= n; x++) { int cnt = 0; if (a[x] != b[x]) { for (int y = la[x]; y; y = ne[y]) cnt += a[w[y]] != b[w[y]]; if (cnt > 2) { cout << -1 << endl; return 0; } if (cnt == 1) cnt1++; s1[x] = cnt; s2[x] = cnt - (a[fa[x]] != b[fa[x]]); if (cnt == 0) cnt1 += 2; } else { if (sw[x] && b[x]) { for (int y = la[x]; y; y = ne[y]) cnt += a[w[y]] != b[w[y]]; if (cnt == 2 && a[fa[x]] != b[fa[x]]) { cnt2++; s1[x] = 100; for (int y = la[x]; y; y = ne[y]) { int z = w[y]; if (z != fa[x] && a[z] != b[z] && sw[z]) { cnt2 = 100; } } } } } } if (cnt1 == 2 && cnt2 == 0) { int x, y, z, X, Y, l = 0; for (int i = 1; i <= n; i++) { if (s1[i] == 1) y = x, x = i; if (a[i] != b[i] && (l == 0 || dep[i] < dep[l])) l = i; } if (sw[x] && sw[y]) { if (dep[x] > dep[y]) swap(x, y); X = x, z = Y = nx[y]; vector<int> a0; while (y != x) a0.push_back(y), y = fa[y]; a0.push_back(x); reverse(a0.begin(), a0.end()); int sum = 0, sum2 = 0; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k, ans2 = (a0.size() + 1) * (a0.size() - k) - 2 * sum; if (tag1) { cout << ans1 << ' ' << ans2 << ' ' << sum << endl; } if (tag1) { cout << 1 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } if (sw[x] + sw[y] == 1) { if (sw[x]) swap(x, y); X = x, Y = nx[y]; vector<int> a1, a2, a0; for (; x != l; x = fa[x]) a1.push_back(x); a1.push_back(l); for (; y != l; y = fa[y]) a2.push_back(y); a0 = a1; while (a2.size()) a0.push_back(a2.back()), a2.pop_back(); int sum = 0, sum2 = 0; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k, ans2 = (a0.size() + 1) * (a0.size() - k) - 2 * sum; if (tag1) { cout << ans1 << ' ' << ans2 << ' ' << sum << endl; } if (tag1) { cout << 2 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } cout << -1 << endl; return 0; } if (cnt1 == 4 && cnt2 == 1) { int x, y, u, X, Y, l = 0; for (int i = 1; i <= n; i++) if (s1[i] == 100) u = i; for (int i = 1; i <= n; i++) { if (s1[i] == 1 && s2[i] == 0 && !sw[i]) y = x, x = i; if (a[i] != b[i] && (l == 0 || dep[i] < dep[l])) l = i; } if (fa[l] == u) { cout << -1 << endl; return 0; } static int tag0[N]; X = x, Y = y; assert(sw[l]); assert(a[l] != b[l]); int x0 = x, y0 = y; while (x0 != l && x0 != u) { assert(a[x0] != b[x0]); assert(sw[x0] == 0); tag0[x0] = 1; x0 = fa[x0]; } while (y0 != l && y0 != u) { assert(a[y0] != b[y0]); assert(sw[y0] == 0); tag0[y0] = 1; y0 = fa[y0]; } assert(x0 != y0); int u0 = fa[u]; assert(sw[u] && a[u] == b[u]); while (u0 != l) { assert(sw[u0]); assert(a[u0] != b[u0]); tag0[u0] = 1; u0 = fa[u0]; } tag0[l] = 1; for (int i = 1; i <= n; i++) { if (tag0[i] != (a[i] != b[i])) { cout << -1 << endl; return 0; } assert(tag0[i] == (a[i] != b[i])); } vector<int> a1, a2, a0; int tag = 0; for (; x != l; x = fa[x]) a1.push_back(x), tag |= 1 * (x == u); for (; y != l; y = fa[y]) a2.push_back(y), tag |= 2 * (y == u); if (tag == 1) swap(a1, a2); a0 = a1; a0.push_back(l); while (a2.size()) { if (a2.back() != u) a0.push_back(a2.back()); a2.pop_back(); } int sum = 0, sum2 = 0; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k, ans2 = (a0.size() + 1) * (a0.size() - k) - 2 * sum; if (tag1) { cout << ans1 << ' ' << ans2 << ' ' << sum << endl; } if (tag1) { cout << l << ' ' << u << ' ' << dep[l] << ' ' << dep[u] << ' ' << dep[X] << ' ' << dep[Y] << ' ' << sw[u] << ' ' << nx[u] << endl; cout << 3 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } cout << -1 << endl; return 0; } int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0, cnt5 = 0; for (int x = 1; x <= n; x++) { int cnt = 0; if (a[x] == b[x]) { for (int y = la[x]; y; y = ne[y]) if (fa[x] != w[y]) cnt += a[w[y]] != b[w[y]]; if (cnt == 2) cnt1++; if (cnt == 1) cnt3++; if (cnt > 2) cnt4++; } else { cnt5++; for (int y = la[x]; y; y = ne[y]) if (fa[x] != w[y]) cnt += a[w[y]] != b[w[y]]; if (cnt == 0) cnt2++; if (cnt > 1) cnt4++; } s1[x] = cnt; } if (!cnt5) { cout << 0 << ' ' << ans << endl; return 0; } if (cnt4) { cout << -1 << endl; return 0; } if (cnt1 == 1 && cnt2 == 2) { int x, y, u, v, X, Y, z; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && a[fa[i]] == b[fa[i]]) v = u, u = i; if (a[i] != b[i] && s1[i] == 0) y = x, x = i; } X = x, Y = y; z = fa[u]; assert(z == fa[v]); if (sw[v]) swap(u, v); vector<int> a1, a2, a0; for (; x != u && x != v; x = fa[x]) a1.push_back(x); a1.push_back(x); for (; y != u && y != v; y = fa[y]) a2.push_back(y); a2.push_back(y); if (a2.back() == u) swap(a1, a2); a0 = a1; while (a2.size()) a0.push_back(a2.back()), a2.pop_back(); int sum = 0, sum2 = 0; while (!sw[z] && z != r) sum2 += 2, z = fa[z]; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k - 2 * sum, ans2 = (a0.size() + 1) * (a0.size() - k); if (tag1) { cout << 4 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } if (cnt3 == 1 && cnt2 == 1) { int x, y, z, X, Y; for (int i = 1; i <= n; i++) { if (a[i] != b[i] && a[fa[i]] == b[fa[i]]) x = i; if (a[i] != b[i] && s1[i] == 0) y = i; } X = fa[x]; Y = y; z = fa[x]; vector<int> a0; while (y != x) a0.push_back(y), y = fa[y]; a0.push_back(x); reverse(a0.begin(), a0.end()); int sum = 0, sum2 = 0; while (!sw[z] && z != r) sum2 += 2, z = fa[z]; for (int i = 0; i < a0.size(); i++) sum += sw[a0[i]]; int k = 0; for (int i = 0; i < a0.size(); i++) if (a[a0[i]] == b[a0[0]]) { k = i; break; } for (int i = 0; i < a0.size(); i++) if (a[a0[(i + k) % a0.size()]] != b[a0[i]]) { cout << -1 << endl; return 0; } long long ans1 = (a0.size() + 1) * k - 2 * sum, ans2 = (a0.size() + 1) * (a0.size() - k); if (tag1) { cout << 5 << endl; } cout << min(X, Y) << ' ' << max(X, Y) << ' '; cout << ans + sum2 + min(ans1, ans2) << endl; return 0; } cout << -1 << endl; } ```
#include <bits/stdc++.h> using namespace std; struct edge { int v, nxt; } e[500005]; int n, k, a[200005], b[200005], h[200005], t, rt, d[200005], f[200005], ct, fl; int st[200005], tp, q[200005], qt, dis[200005], vis[200005], srt; void add(int u, int v) { e[++t].v = v; e[t].nxt = h[u]; h[u] = t; } void dfs1(int u, int fa, int dep) { f[u] = fa; d[u] = dep; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs1(v, u, dep + 1); } } void dfs3(int u, int fa) { st[tp++] = u; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa || a[v] == b[v]) continue; dfs3(v, u); return; } } void dfs2(int u, int fa) { int q = 0; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs2(v, u); if (fl >= 2) return; if (a[v] != b[v]) q++; } if (q && a[u] == b[u]) { if (q == 1 || q == 2) fl++; if (q >= 3) fl = 2; if (fl >= 2) return; srt = u; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa || a[v] == b[v]) continue; dfs3(v, u); if (q == 2) reverse(st, st + tp); } } } void dfs4(int u, int fa) { for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (vis[v]) continue; vis[v] = 1; dis[v] = dis[u] + 1; dfs4(v, u); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } for (int i = 1; i <= n; i++) if (b[i] == 0) rt = i; dfs1(rt, 0, 0); int u; for (int i = 1; i <= n; i++) if (a[i] == 0) u = i; int nw = u; while (nw != rt) { q[qt++] = nw; swap(a[nw], a[f[nw]]); nw = f[nw]; } q[qt++] = rt; for (int i = 1; i <= n; i++) if (a[i] != b[i]) ct++; if (!ct) { printf("0 %d\n", d[u]); return 0; } dfs2(rt, 0); if (fl != 1 || tp != ct) { printf("-1\n"); return 0; } for (int i = 1; i < tp; i++) if (b[st[i]] == a[st[0]]) { k = i; break; } for (int i = 0; i < tp; i++) if (b[st[(i + k) % tp]] != a[st[i]]) { printf("-1\n"); return 0; } if (d[st[0]] >= d[st[1]]) printf("%d %d ", min(st[0], st[tp - 1]), max(st[0], st[tp - 1])); else printf("%d %d ", min(srt, st[tp - 1]), max(srt, st[tp - 1])); for (int i = 0; i < qt; i++) dis[q[i]] = 0, vis[q[i]] = 1; for (int i = 0; i < qt; i++) dfs4(q[i], 0); int ffl = 0; for (int i = 0; i < tp; i++) if (dis[st[i]] == 0) ffl = 1; if (!ffl) { long long ans = d[u] + dis[srt] * 2 + 1ll * min(k, tp - k) * (tp + 1); printf("%lld\n", ans); return 0; } k = tp - k; if (dis[st[tp - 1]] < d[st[tp - 1]] - d[srt]) { int q = (d[st[tp - 1]] - d[srt]) - dis[st[tp - 1]]; long long ans = d[u] + min(1ll * k * (tp + 1) - 2 * q, 1ll * (tp - k) * (tp + 1)); printf("%lld\n", ans); } else { int q = (d[st[0]] - d[srt]) - dis[st[0]]; long long ans = d[u] + min(1ll * k * (tp + 1), 1ll * (tp - k) * (tp + 1) - 2 * q); printf("%lld\n", ans); } return 0; }
### Prompt Please create a solution in Cpp to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct edge { int v, nxt; } e[500005]; int n, k, a[200005], b[200005], h[200005], t, rt, d[200005], f[200005], ct, fl; int st[200005], tp, q[200005], qt, dis[200005], vis[200005], srt; void add(int u, int v) { e[++t].v = v; e[t].nxt = h[u]; h[u] = t; } void dfs1(int u, int fa, int dep) { f[u] = fa; d[u] = dep; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs1(v, u, dep + 1); } } void dfs3(int u, int fa) { st[tp++] = u; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa || a[v] == b[v]) continue; dfs3(v, u); return; } } void dfs2(int u, int fa) { int q = 0; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs2(v, u); if (fl >= 2) return; if (a[v] != b[v]) q++; } if (q && a[u] == b[u]) { if (q == 1 || q == 2) fl++; if (q >= 3) fl = 2; if (fl >= 2) return; srt = u; for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa || a[v] == b[v]) continue; dfs3(v, u); if (q == 2) reverse(st, st + tp); } } } void dfs4(int u, int fa) { for (int i = h[u]; i; i = e[i].nxt) { int v = e[i].v; if (vis[v]) continue; vis[v] = 1; dis[v] = dis[u] + 1; dfs4(v, u); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &b[i]); for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } for (int i = 1; i <= n; i++) if (b[i] == 0) rt = i; dfs1(rt, 0, 0); int u; for (int i = 1; i <= n; i++) if (a[i] == 0) u = i; int nw = u; while (nw != rt) { q[qt++] = nw; swap(a[nw], a[f[nw]]); nw = f[nw]; } q[qt++] = rt; for (int i = 1; i <= n; i++) if (a[i] != b[i]) ct++; if (!ct) { printf("0 %d\n", d[u]); return 0; } dfs2(rt, 0); if (fl != 1 || tp != ct) { printf("-1\n"); return 0; } for (int i = 1; i < tp; i++) if (b[st[i]] == a[st[0]]) { k = i; break; } for (int i = 0; i < tp; i++) if (b[st[(i + k) % tp]] != a[st[i]]) { printf("-1\n"); return 0; } if (d[st[0]] >= d[st[1]]) printf("%d %d ", min(st[0], st[tp - 1]), max(st[0], st[tp - 1])); else printf("%d %d ", min(srt, st[tp - 1]), max(srt, st[tp - 1])); for (int i = 0; i < qt; i++) dis[q[i]] = 0, vis[q[i]] = 1; for (int i = 0; i < qt; i++) dfs4(q[i], 0); int ffl = 0; for (int i = 0; i < tp; i++) if (dis[st[i]] == 0) ffl = 1; if (!ffl) { long long ans = d[u] + dis[srt] * 2 + 1ll * min(k, tp - k) * (tp + 1); printf("%lld\n", ans); return 0; } k = tp - k; if (dis[st[tp - 1]] < d[st[tp - 1]] - d[srt]) { int q = (d[st[tp - 1]] - d[srt]) - dis[st[tp - 1]]; long long ans = d[u] + min(1ll * k * (tp + 1) - 2 * q, 1ll * (tp - k) * (tp + 1)); printf("%lld\n", ans); } else { int q = (d[st[0]] - d[srt]) - dis[st[0]]; long long ans = d[u] + min(1ll * k * (tp + 1), 1ll * (tp - k) * (tp + 1) - 2 * q); printf("%lld\n", ans); } return 0; } ```
#include <bits/stdc++.h> inline long long min(long long x, long long y) { return x < y ? x : y; } int A[200002], B[200002], a[200002], O[200002], P[200002], Q, b[400004], c[400004], f[200002], h[200002], n, s, t; bool d[200002]; inline int dis(int u, int v) { int w = 0; for (; u != v; h[u] < h[v] ? v = f[v] : u = f[u]) w++; return w; } void dfs(int u) { for (int i = a[u]; i; i = b[i]) if (c[i] != f[u]) f[c[i]] = u, h[c[i]] = h[u] + 1, dfs(c[i]); } int i, u, v, w; int main() { scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", A + i); for (i = 1; i <= n; i++) scanf("%d", B + i); for (i = 1; i < n; i++) scanf("%d%d", &u, &v), b[++t] = a[u], c[a[u] = t] = v, b[++t] = a[v], c[a[v] = t] = u; for (i = 1, u = 0; i <= n; i++) s = !A[i] ? i : s, t = !B[i] ? i : t; for (dfs(t), i = s; i; i = f[i]) A[i] = A[f[i]]; for (i = 1; i <= n; i++) if (A[i] != B[i] && h[u] < h[i]) u = i; if (!u) return 0 & printf("0 %d\n", h[s]); for (i = u; i; i = f[i]) d[i] = true, w = A[i] != B[i] ? i : w; for (i = 1, v = w = f[w]; i <= n; i++) if (!d[i] && A[i] != B[i] && h[v] <= h[i]) v = i; for (i = v; !d[i]; i = f[i]) d[i] = true; if (i != w) return 0 & puts("-1"); for (i = 1; i <= n; i++) if (!d[i] && A[i] != B[i]) return 0 & puts("-1"); for (i = u; i != w; i = f[i]) O[++Q] = A[i], P[Q] = B[i]; for (i = 1; i << 1 <= Q; i++) O[i] ^= O[Q - i + 1] ^= O[i] ^= O[Q - i + 1], P[i] ^= P[Q - i + 1] ^= P[i] ^= P[Q - i + 1]; for (i = v; i != w; i = f[i]) O[++Q] = A[i], P[Q] = B[i]; for (i = 1, w = 0; !w; i++) if (O[1] == P[i]) w = i; for (i = 0; i <= Q - w; i++) if (O[i + 1] != P[w + i]) return 0 & puts("-1"); for (; i < Q; i++) if (O[i + 1] != P[i - Q + w]) return 0 & puts("-1"); return 0 * printf("%d %d %d\n", u < v ? u : v, u < v ? v : u, min(dis(s, u) + (Q + 1ll) * (Q - w) + dis(v, t) + 1, dis(s, v) + (Q + 1ll) * (w - 2) + dis(u, t) + 1)); }
### Prompt Please formulate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> inline long long min(long long x, long long y) { return x < y ? x : y; } int A[200002], B[200002], a[200002], O[200002], P[200002], Q, b[400004], c[400004], f[200002], h[200002], n, s, t; bool d[200002]; inline int dis(int u, int v) { int w = 0; for (; u != v; h[u] < h[v] ? v = f[v] : u = f[u]) w++; return w; } void dfs(int u) { for (int i = a[u]; i; i = b[i]) if (c[i] != f[u]) f[c[i]] = u, h[c[i]] = h[u] + 1, dfs(c[i]); } int i, u, v, w; int main() { scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", A + i); for (i = 1; i <= n; i++) scanf("%d", B + i); for (i = 1; i < n; i++) scanf("%d%d", &u, &v), b[++t] = a[u], c[a[u] = t] = v, b[++t] = a[v], c[a[v] = t] = u; for (i = 1, u = 0; i <= n; i++) s = !A[i] ? i : s, t = !B[i] ? i : t; for (dfs(t), i = s; i; i = f[i]) A[i] = A[f[i]]; for (i = 1; i <= n; i++) if (A[i] != B[i] && h[u] < h[i]) u = i; if (!u) return 0 & printf("0 %d\n", h[s]); for (i = u; i; i = f[i]) d[i] = true, w = A[i] != B[i] ? i : w; for (i = 1, v = w = f[w]; i <= n; i++) if (!d[i] && A[i] != B[i] && h[v] <= h[i]) v = i; for (i = v; !d[i]; i = f[i]) d[i] = true; if (i != w) return 0 & puts("-1"); for (i = 1; i <= n; i++) if (!d[i] && A[i] != B[i]) return 0 & puts("-1"); for (i = u; i != w; i = f[i]) O[++Q] = A[i], P[Q] = B[i]; for (i = 1; i << 1 <= Q; i++) O[i] ^= O[Q - i + 1] ^= O[i] ^= O[Q - i + 1], P[i] ^= P[Q - i + 1] ^= P[i] ^= P[Q - i + 1]; for (i = v; i != w; i = f[i]) O[++Q] = A[i], P[Q] = B[i]; for (i = 1, w = 0; !w; i++) if (O[1] == P[i]) w = i; for (i = 0; i <= Q - w; i++) if (O[i + 1] != P[w + i]) return 0 & puts("-1"); for (; i < Q; i++) if (O[i + 1] != P[i - Q + w]) return 0 & puts("-1"); return 0 * printf("%d %d %d\n", u < v ? u : v, u < v ? v : u, min(dis(s, u) + (Q + 1ll) * (Q - w) + dis(v, t) + 1, dis(s, v) + (Q + 1ll) * (w - 2) + dis(u, t) + 1)); } ```
#include <bits/stdc++.h> using namespace std; vector<int> no, a[200010]; int n, p[200010], q[200010], x, y, s1, s2, an1, an2, an3, an4; bool ex = 1; bool get(int x, int fa, int mu) { no.emplace_back(x); if (x == mu) return 1; for (int y : a[x]) if (y != fa && get(y, x, mu)) return 1; no.pop_back(); return 0; } int dis(int x, int y) { no.clear(); get(x, 0, y); return no.size() - 1; } void dfs(int x, int fa) { for (auto y : a[x]) if (y != fa) dfs(y, x); if (p[x] != q[x]) { int s = 0; for (auto y : a[x]) if (y != fa && p[y] != q[y]) s++; if (s == 0) { an3++; if (an1) an2 = x; else { an1 = x; no.clear(); get(x, 0, s2); for (int i = 0; i < no.size(); i++) if (p[no[i]] == q[no[i]]) { an2 = an4 = no[i]; break; } } } } else { int s = 0; for (auto y : a[x]) if (y != fa && p[y] != q[y]) s++; if (s == 2) { an3--; an4 = x; } } } int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> p[i]; for (int i = 1; i <= n; i++) cin >> q[i]; for (int i = 1; i < n; i++) { cin >> x >> y; a[x].emplace_back(y); a[y].emplace_back(x); } s1 = 0, s2 = 0; for (int i = 1; i <= n; i++) { if (!p[i]) s1 = i; if (!q[i]) s2 = i; } no.clear(); get(s1, 0, s2); for (int i = 1; i < no.size(); i++) swap(p[no[i - 1]], p[no[i]]); int an = 1; for (int i = 1; i <= n; i++) if (p[i] != q[i]) an = 0; if (an) { cout << "0 " << dis(s1, s2) << endl; return 0; } dfs(s2, 0); if (an3 != 1) { cout << "-1" << endl; return 0; } no.clear(); get(an1, 0, an2); for (int i = 0; i < no.size(); i++) if (no[i] == an4) no.erase(no.begin() + i); int g = 0; long long k = no.size(); for (int i = 0; i < no.size(); i++) if (q[no[i]] == p[no[0]]) g = i; for (int i = 0; i < no.size(); i++) if (p[no[i]] != q[no[(i + g) % no.size()]]) { cout << "-1" << endl; return 0; } cout << min(an1, an2) << ' ' << max(an1, an2) << ' ' << min((k + 1) * (g - 1) + 1 + dis(s1, an1) + dis(s2, an2), (k + 1) * (k - g - 1) + 1 + dis(s2, an1) + dis(s1, an2)) << endl; return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<int> no, a[200010]; int n, p[200010], q[200010], x, y, s1, s2, an1, an2, an3, an4; bool ex = 1; bool get(int x, int fa, int mu) { no.emplace_back(x); if (x == mu) return 1; for (int y : a[x]) if (y != fa && get(y, x, mu)) return 1; no.pop_back(); return 0; } int dis(int x, int y) { no.clear(); get(x, 0, y); return no.size() - 1; } void dfs(int x, int fa) { for (auto y : a[x]) if (y != fa) dfs(y, x); if (p[x] != q[x]) { int s = 0; for (auto y : a[x]) if (y != fa && p[y] != q[y]) s++; if (s == 0) { an3++; if (an1) an2 = x; else { an1 = x; no.clear(); get(x, 0, s2); for (int i = 0; i < no.size(); i++) if (p[no[i]] == q[no[i]]) { an2 = an4 = no[i]; break; } } } } else { int s = 0; for (auto y : a[x]) if (y != fa && p[y] != q[y]) s++; if (s == 2) { an3--; an4 = x; } } } int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> p[i]; for (int i = 1; i <= n; i++) cin >> q[i]; for (int i = 1; i < n; i++) { cin >> x >> y; a[x].emplace_back(y); a[y].emplace_back(x); } s1 = 0, s2 = 0; for (int i = 1; i <= n; i++) { if (!p[i]) s1 = i; if (!q[i]) s2 = i; } no.clear(); get(s1, 0, s2); for (int i = 1; i < no.size(); i++) swap(p[no[i - 1]], p[no[i]]); int an = 1; for (int i = 1; i <= n; i++) if (p[i] != q[i]) an = 0; if (an) { cout << "0 " << dis(s1, s2) << endl; return 0; } dfs(s2, 0); if (an3 != 1) { cout << "-1" << endl; return 0; } no.clear(); get(an1, 0, an2); for (int i = 0; i < no.size(); i++) if (no[i] == an4) no.erase(no.begin() + i); int g = 0; long long k = no.size(); for (int i = 0; i < no.size(); i++) if (q[no[i]] == p[no[0]]) g = i; for (int i = 0; i < no.size(); i++) if (p[no[i]] != q[no[(i + g) % no.size()]]) { cout << "-1" << endl; return 0; } cout << min(an1, an2) << ' ' << max(an1, an2) << ' ' << min((k + 1) * (g - 1) + 1 + dis(s1, an1) + dis(s2, an2), (k + 1) * (k - g - 1) + 1 + dis(s2, an1) + dis(s1, an2)) << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } vector<int> V[200010], cir; int fa[200010], dep[200010], a[200010], b[200010], n, Rt, lp, lq, pa, pb; void dfs(int rt, int pr) { for (int i = 0; i < V[rt].size(); i++) { if (V[rt][i] == pr) continue; fa[V[rt][i]] = rt; dep[V[rt][i]] = dep[rt] + 1; dfs(V[rt][i], rt); } } bool findloop() { cir.clear(); bool vis[200010]; memset(vis, 0, sizeof vis); int p = 0, q = 0, u, v; ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); Rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[Rt]) return 0; lp = p, lq = q; return 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), pa = a[i] == 0 ? i : pa; for (int i = 1; i <= n; i++) b[i] = read(), pb = b[i] == 0 ? i : pb; for (int i = 1, u, v; i < n; i++) u = read(), v = read(), V[u].push_back(v), V[v].push_back(u); dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!findloop()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; static bool vis[200010]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[Rt]; Rt = fa[Rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; }
### Prompt Generate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } vector<int> V[200010], cir; int fa[200010], dep[200010], a[200010], b[200010], n, Rt, lp, lq, pa, pb; void dfs(int rt, int pr) { for (int i = 0; i < V[rt].size(); i++) { if (V[rt][i] == pr) continue; fa[V[rt][i]] = rt; dep[V[rt][i]] = dep[rt] + 1; dfs(V[rt][i], rt); } } bool findloop() { cir.clear(); bool vis[200010]; memset(vis, 0, sizeof vis); int p = 0, q = 0, u, v; ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); Rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[Rt]) return 0; lp = p, lq = q; return 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), pa = a[i] == 0 ? i : pa; for (int i = 1; i <= n; i++) b[i] = read(), pb = b[i] == 0 ? i : pb; for (int i = 1, u, v; i < n; i++) u = read(), v = read(), V[u].push_back(v), V[v].push_back(u); dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!findloop()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; static bool vis[200010]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[Rt]; Rt = fa[Rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; } ```
#include <bits/stdc++.h> inline int read() { char c; int x; for (c = getchar(); !isdigit(c); c = getchar()) ; for (x = 0; isdigit(c); c = getchar()) { x = x * 10 + c - '0'; } return x; } const int N = 1e6 + 5; int n, k, s, t, rs, rt, len, ans0, a[N], b[N], ft[N], dis[N], dit[N], deg[N]; long long ans1; std::vector<int> e[N], ed; bool dfs0(int u, int fa) { if (u == s) { return true; } for (auto v : e[u]) { if (v == fa) { continue; } if (dfs0(v, u)) { std::swap(a[u], a[v]); ans0++; return true; } } return false; } void dfs1(int u, int fa) { ft[u] = fa; dit[u] = dit[fa] + 1; if (a[u] != b[u]) { deg[fa]++; } for (auto v : e[u]) { if (v == fa) { continue; } dfs1(v, u); } } void dfs2(int u, int fa) { dis[u] = dis[fa] + 1; for (auto v : e[u]) { if (v == fa) { continue; } dfs2(v, u); } } bool check0() { for (int u = 1; u <= n; u++) { if (a[u] != b[u]) { return false; } } return true; } bool check1() { rt = -1; for (int u = 1; u <= n; u++) { if (a[u] == b[u]) { if (deg[u] > 2) { return false; } if (deg[u] != 0) { if (rt != -1) { return false; } rt = u; } } else { if (deg[u] > 1) { return false; } if (deg[u] == 0) { ed.push_back(u); } len++; } } if (ed.size() > 2) { return false; } if (ed.size() < 2) { ed.push_back(rt); } rs = s; for (; rs != t && a[rs] == b[rs]; rs = ft[rs]) ; if (rs == t) { rs = rt; } for (int u = ed[0]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = dit[ed[0]] - dit[u]; } } for (int u = ed[1]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = len - (dit[ed[1]] - dit[u] + 1); } } for (int u = ed[0]; u != rt; u = ft[u]) { if (u == rs) { k = len - k; } } return true; } int main() { n = read(); for (int u = 1; u <= n; u++) { a[u] = read(); if (a[u] == 0) { s = u; } } for (int u = 1; u <= n; u++) { b[u] = read(); if (b[u] == 0) { t = u; } } for (int i = 1; i < n; i++) { int u = read(), v = read(); e[u].push_back(v); e[v].push_back(u); } dfs0(t, 0); if (check0()) { printf("0 %d\n", ans0); return 0; } dis[0] = dit[0] = -1; dfs1(t, 0); dfs2(s, 0); if (!check1()) { printf("-1\n"); return 0; } if (rs == rt) { ans1 = dis[rs] + dit[rt] + 1ll * std::min(k, len - k) * (len + 1); } else { ans1 = dis[rs] + dit[rt]; int mid = dis[rt] - dis[rs]; ans1 += std::min(k * (len + 1ll) - mid, (len - k) * (len + 1ll) + mid); } std::sort(ed.begin(), ed.end()); printf("%d %d %lld\n", ed[0], ed[1], ans1); return 0; }
### Prompt Please create a solution in cpp to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> inline int read() { char c; int x; for (c = getchar(); !isdigit(c); c = getchar()) ; for (x = 0; isdigit(c); c = getchar()) { x = x * 10 + c - '0'; } return x; } const int N = 1e6 + 5; int n, k, s, t, rs, rt, len, ans0, a[N], b[N], ft[N], dis[N], dit[N], deg[N]; long long ans1; std::vector<int> e[N], ed; bool dfs0(int u, int fa) { if (u == s) { return true; } for (auto v : e[u]) { if (v == fa) { continue; } if (dfs0(v, u)) { std::swap(a[u], a[v]); ans0++; return true; } } return false; } void dfs1(int u, int fa) { ft[u] = fa; dit[u] = dit[fa] + 1; if (a[u] != b[u]) { deg[fa]++; } for (auto v : e[u]) { if (v == fa) { continue; } dfs1(v, u); } } void dfs2(int u, int fa) { dis[u] = dis[fa] + 1; for (auto v : e[u]) { if (v == fa) { continue; } dfs2(v, u); } } bool check0() { for (int u = 1; u <= n; u++) { if (a[u] != b[u]) { return false; } } return true; } bool check1() { rt = -1; for (int u = 1; u <= n; u++) { if (a[u] == b[u]) { if (deg[u] > 2) { return false; } if (deg[u] != 0) { if (rt != -1) { return false; } rt = u; } } else { if (deg[u] > 1) { return false; } if (deg[u] == 0) { ed.push_back(u); } len++; } } if (ed.size() > 2) { return false; } if (ed.size() < 2) { ed.push_back(rt); } rs = s; for (; rs != t && a[rs] == b[rs]; rs = ft[rs]) ; if (rs == t) { rs = rt; } for (int u = ed[0]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = dit[ed[0]] - dit[u]; } } for (int u = ed[1]; u != rt; u = ft[u]) { if (a[u] == b[ed[0]]) { k = len - (dit[ed[1]] - dit[u] + 1); } } for (int u = ed[0]; u != rt; u = ft[u]) { if (u == rs) { k = len - k; } } return true; } int main() { n = read(); for (int u = 1; u <= n; u++) { a[u] = read(); if (a[u] == 0) { s = u; } } for (int u = 1; u <= n; u++) { b[u] = read(); if (b[u] == 0) { t = u; } } for (int i = 1; i < n; i++) { int u = read(), v = read(); e[u].push_back(v); e[v].push_back(u); } dfs0(t, 0); if (check0()) { printf("0 %d\n", ans0); return 0; } dis[0] = dit[0] = -1; dfs1(t, 0); dfs2(s, 0); if (!check1()) { printf("-1\n"); return 0; } if (rs == rt) { ans1 = dis[rs] + dit[rt] + 1ll * std::min(k, len - k) * (len + 1); } else { ans1 = dis[rs] + dit[rt]; int mid = dis[rt] - dis[rs]; ans1 += std::min(k * (len + 1ll) - mid, (len - k) * (len + 1ll) + mid); } std::sort(ed.begin(), ed.end()); printf("%d %d %lld\n", ed[0], ed[1], ans1); return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; int a[maxn], b[maxn], c[maxn]; int n, s, t; vector<int> g[maxn]; int pa[20][maxn], dep[maxn]; void buildtree(int x, int fa) { pa[0][x] = fa; dep[x] = dep[fa] + 1; for (int i = 0; i < g[x].size(); i++) { int to = g[x][i]; if (to == fa) continue; buildtree(to, x); } } inline int getlca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = 0; i < 20; i++) { if ((dep[x] - dep[y]) >> i & 1) x = pa[i][x]; } if (x == y) return x; for (int i = 19; i >= 0; i--) { if (pa[i][x] != pa[i][y]) { x = pa[i][x]; y = pa[i][y]; } } return pa[0][x]; } int vis[maxn]; vector<int> getpath(int fr, int to) { vector<int> res = vector<int>(); while (fr != to) { vis[fr]++; res.push_back(fr); fr = pa[0][fr]; } return res; } vector<int> dif; pair<int, int> checkvalid() { for (int i = 1; i <= n; i++) c[i] = a[i]; buildtree(t, 0); for (int k = 1; k < 20; k++) { for (int i = 1; i <= n; i++) { pa[k][i] = pa[k - 1][pa[k - 1][i]]; } } int x = s; while (x != t) { swap(c[x], c[pa[0][x]]); x = pa[0][x]; } dif.clear(); for (int i = 1; i <= n; i++) { if (b[i] != c[i]) { dif.push_back(i); } } if (dif.empty()) return make_pair(0, 0); int hg = dif[0]; for (int i = 1; i < dif.size(); i++) if (dep[dif[i]] < dep[hg]) hg = dif[i]; int lca = pa[0][hg]; for (int i = 0; i < dif.size(); i++) { if (getlca(dif[i], lca) != lca) { return make_pair(-1, -1); } } int u = dif[0]; for (int i = 1; i < dif.size(); i++) { if (dep[dif[i]] > dep[u]) u = dif[i]; } vector<int> lft = getpath(u, lca); int v = 0; for (int i = 0; i < dif.size(); i++) { if (!vis[dif[i]] && (!v || dep[dif[i]] > dep[v])) v = dif[i]; } if (v) { vector<int> rht = getpath(v, lca); reverse(rht.begin(), rht.end()); for (int i = 0; i < rht.size(); i++) lft.push_back(rht[i]); for (int i = 0; i < lft.size(); i++) if (vis[lft[i]] > 1) return make_pair(-1, -1); } else v = lca; for (int i = 0; i < dif.size(); i++) if (!vis[dif[i]]) return make_pair(-1, -1); dif.swap(lft); for (int i = 0; i < dif.size(); i++) { } for (int i = 0; i < dif.size(); i++) { } int p = 0; while (p < dif.size() && c[dif[p]] != b[dif[0]]) p++; if (p == dif.size()) return make_pair(-1, -1); for (int i = 1; i < dif.size(); i++) { p = (p + 1) % dif.size(); if (c[dif[p]] != b[dif[i]]) return make_pair(-1, -1); } return make_pair(u, v); } int getdist(int x, int y) { int lca = getlca(x, y); return dep[x] + dep[y] - 2 * dep[lca]; } long long getans(int u, int v) { long long ans; { int p = 0; while (p < dif.size() && b[dif[p]] != a[dif[0]]) p++; if (u == dif[0]) ; else p = dif.size() - p; ans = (p - 1) * 1ll * (getdist(u, v) + 1); } ans += getdist(s, u); ans += getdist(v, t); ans++; return ans; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) t = i; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); g[u].push_back(v); g[v].push_back(u); } pair<int, int> res = checkvalid(); if (res.first == -1) { printf("-1\n"); return 0; } if (res.first == 0) { printf("0 %d\n", dep[s] - dep[t]); return 0; } if (res.first > res.second) swap(res.first, res.second); printf("%d %d ", res.first, res.second); printf("%I64d\n", min(getans(res.first, res.second), getans(res.second, res.first))); return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; int a[maxn], b[maxn], c[maxn]; int n, s, t; vector<int> g[maxn]; int pa[20][maxn], dep[maxn]; void buildtree(int x, int fa) { pa[0][x] = fa; dep[x] = dep[fa] + 1; for (int i = 0; i < g[x].size(); i++) { int to = g[x][i]; if (to == fa) continue; buildtree(to, x); } } inline int getlca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = 0; i < 20; i++) { if ((dep[x] - dep[y]) >> i & 1) x = pa[i][x]; } if (x == y) return x; for (int i = 19; i >= 0; i--) { if (pa[i][x] != pa[i][y]) { x = pa[i][x]; y = pa[i][y]; } } return pa[0][x]; } int vis[maxn]; vector<int> getpath(int fr, int to) { vector<int> res = vector<int>(); while (fr != to) { vis[fr]++; res.push_back(fr); fr = pa[0][fr]; } return res; } vector<int> dif; pair<int, int> checkvalid() { for (int i = 1; i <= n; i++) c[i] = a[i]; buildtree(t, 0); for (int k = 1; k < 20; k++) { for (int i = 1; i <= n; i++) { pa[k][i] = pa[k - 1][pa[k - 1][i]]; } } int x = s; while (x != t) { swap(c[x], c[pa[0][x]]); x = pa[0][x]; } dif.clear(); for (int i = 1; i <= n; i++) { if (b[i] != c[i]) { dif.push_back(i); } } if (dif.empty()) return make_pair(0, 0); int hg = dif[0]; for (int i = 1; i < dif.size(); i++) if (dep[dif[i]] < dep[hg]) hg = dif[i]; int lca = pa[0][hg]; for (int i = 0; i < dif.size(); i++) { if (getlca(dif[i], lca) != lca) { return make_pair(-1, -1); } } int u = dif[0]; for (int i = 1; i < dif.size(); i++) { if (dep[dif[i]] > dep[u]) u = dif[i]; } vector<int> lft = getpath(u, lca); int v = 0; for (int i = 0; i < dif.size(); i++) { if (!vis[dif[i]] && (!v || dep[dif[i]] > dep[v])) v = dif[i]; } if (v) { vector<int> rht = getpath(v, lca); reverse(rht.begin(), rht.end()); for (int i = 0; i < rht.size(); i++) lft.push_back(rht[i]); for (int i = 0; i < lft.size(); i++) if (vis[lft[i]] > 1) return make_pair(-1, -1); } else v = lca; for (int i = 0; i < dif.size(); i++) if (!vis[dif[i]]) return make_pair(-1, -1); dif.swap(lft); for (int i = 0; i < dif.size(); i++) { } for (int i = 0; i < dif.size(); i++) { } int p = 0; while (p < dif.size() && c[dif[p]] != b[dif[0]]) p++; if (p == dif.size()) return make_pair(-1, -1); for (int i = 1; i < dif.size(); i++) { p = (p + 1) % dif.size(); if (c[dif[p]] != b[dif[i]]) return make_pair(-1, -1); } return make_pair(u, v); } int getdist(int x, int y) { int lca = getlca(x, y); return dep[x] + dep[y] - 2 * dep[lca]; } long long getans(int u, int v) { long long ans; { int p = 0; while (p < dif.size() && b[dif[p]] != a[dif[0]]) p++; if (u == dif[0]) ; else p = dif.size() - p; ans = (p - 1) * 1ll * (getdist(u, v) + 1); } ans += getdist(s, u); ans += getdist(v, t); ans++; return ans; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!a[i]) s = i; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); if (!b[i]) t = i; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); g[u].push_back(v); g[v].push_back(u); } pair<int, int> res = checkvalid(); if (res.first == -1) { printf("-1\n"); return 0; } if (res.first == 0) { printf("0 %d\n", dep[s] - dep[t]); return 0; } if (res.first > res.second) swap(res.first, res.second); printf("%d %d ", res.first, res.second); printf("%I64d\n", min(getans(res.first, res.second), getans(res.second, res.first))); return 0; } ```
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } vector<int> V[200010], cir; int fa[200010], dep[200010], a[200010], b[200010], n, Rt, lp, lq, pa, pb; void dfs(int rt, int pr) { for (int i = 0; i < V[rt].size(); i++) { if (V[rt][i] == pr) continue; fa[V[rt][i]] = rt; dep[V[rt][i]] = dep[rt] + 1; dfs(V[rt][i], rt); } } bool findloop() { cir.clear(); bool vis[200010]; memset(vis, 0, sizeof vis); int p = 0, q = 0, u, v; ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); Rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[Rt]) return 0; lp = p, lq = q; return 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), pa = a[i] == 0 ? i : pa; for (int i = 1; i <= n; i++) b[i] = read(), pb = b[i] == 0 ? i : pb; for (int i = 1, u, v; i < n; i++) u = read(), v = read(), V[u].push_back(v), V[v].push_back(u); dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!findloop()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; for (int i = 1; i < len; i++) if (b[cir[(i + gap) % len]] != a[cir[i]]) { printf("-1\n"); return 0; } static bool vis[200010]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[Rt]; Rt = fa[Rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } vector<int> V[200010], cir; int fa[200010], dep[200010], a[200010], b[200010], n, Rt, lp, lq, pa, pb; void dfs(int rt, int pr) { for (int i = 0; i < V[rt].size(); i++) { if (V[rt][i] == pr) continue; fa[V[rt][i]] = rt; dep[V[rt][i]] = dep[rt] + 1; dfs(V[rt][i], rt); } } bool findloop() { cir.clear(); bool vis[200010]; memset(vis, 0, sizeof vis); int p = 0, q = 0, u, v; ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && dep[i] > dep[p]) p = i; if (!p) return 1; for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i; if (q) { reverse(cir.begin(), cir.end()); for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u]) ; } else q = fa[cir.back()]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vis[i]) return 0; for (u = p, v = q; u != v; u = fa[u]) if (dep[u] < dep[v]) swap(u, v); Rt = u; if (cir.size() != dep[p] + dep[q] - 2 * dep[Rt]) return 0; lp = p, lq = q; return 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), pa = a[i] == 0 ? i : pa; for (int i = 1; i <= n; i++) b[i] = read(), pb = b[i] == 0 ? i : pb; for (int i = 1, u, v; i < n; i++) u = read(), v = read(), V[u].push_back(v), V[v].push_back(u); dep[0] = -1; dfs(pb, 0); for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]); long long ans = dep[pa]; if (!findloop()) { printf("-1\n"); return 0; } if (!cir.size()) { printf("0 %d\n", ans); return 0; } int gap = 0, len = cir.size(); for (int i = 0; i < len; i++) if (b[cir[i]] == a[cir[0]]) gap = i; for (int i = 1; i < len; i++) if (b[cir[(i + gap) % len]] != a[cir[i]]) { printf("-1\n"); return 0; } static bool vis[200010]; for (int i = pa; i; i = fa[i]) vis[i] = 1; if (vis[cir[0]] || vis[cir.back()]) { int po = cir.size(); for (int i = 0; i < cir.size(); i++) if (!vis[cir[i]]) { po = i; break; } ans = ans - po + min(po + gap * 1ll * (len + 1), abs((len - gap) * 1ll * (len + 1) - po)); } else ans = (ans + min(gap, len - gap) * 1ll * (len + 1)); for (; !vis[Rt]; Rt = fa[Rt]) ans += 2; if (lp > lq) swap(lq, lp); printf("%d %d %lld\n", lp, lq, ans); return 0; } ```
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f = ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 200005; int n, s0, t0, s, t, tp; vector<int> e[N], ch[N]; int a[N], b[N], c[N], f[N]; deque<int> id; int find(int *a, int v) { for (int i = (1); i <= (n); i++) if (a[i] == v) return i; return 0; } int check(int *a, int *b) { for (int i = (1); i <= (n); i++) if (a[i] != b[i]) return 0; return 1; } int fa[N], dep[N], anc[N][20]; void dfs(int x, int pre = 0, int d = 0) { anc[x][0] = fa[x] = pre, dep[x] = d; for (int i = (1); i <= (19); i++) anc[x][i] = anc[anc[x][i - 1]][i - 1]; for (auto y : e[x]) if (y != pre) dfs(y, x, d + 1); } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = (19); i >= (0); i--) if (dep[x] - (1 << i) >= dep[y]) x = anc[x][i]; if (x == y) return x; for (int i = (19); i >= (0); i--) if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i]; return fa[x]; } int dis(int x, int y) { return dep[x] + dep[y] - 2 * dep[LCA(x, y)]; } void getc() { s0 = find(a, 0), t0 = find(b, 0); dfs(t0); for (int i = (1); i <= (n); i++) c[i] = a[i]; for (int x = s0; x != t0; x = fa[x]) id.push_back(x), swap(c[x], c[fa[x]]); id.push_back(t0); if (check(b, c)) printf("0 %d\n", dep[s0]), exit(0); } void NO() { puts("-1"); exit(0); } vector<int> cid; void dfs_ch(int x, int pre = 0) { cid.push_back(x); if (x == t) tp = (int)cid.size() - 1; for (auto y : ch[x]) if (y != pre) dfs_ch(y, x); } int main() { n = read(); for (int i = (1); i <= (n); i++) a[i] = read(); int Test = a[1] == 3779; for (int i = (1); i <= (n); i++) b[i] = read(); for (int i = (1); i <= (n - 1); i++) { int x = read(), y = read(); e[x].push_back(y), e[y].push_back(x); } getc(); deque<int> ID = id; while ((int)id.size() >= 2 && b[id[0]] == c[id[0]]) id.pop_front(); while ((int)id.size() >= 2 && b[id[(int)id.size() - 2]] == c[id[(int)id.size() - 2]]) id.pop_back(); assert(!id.empty()); s = id.front(), t = id.back(); if (b[id[0]] != c[id[0]]) { for (auto i : id) f[i] = 1; } else { int x = -1; for (int i = (1); i <= (n); i++) if (b[i] != c[i]) if (x == -1 || dis(i, t0) < dis(x, t0)) x = i; assert(x != -1); for (auto y : e[x]) if (dis(y, t0) < dis(x, t0)) { f[s = t = y] = 1; break; } assert(s != 0); } for (int i = (1); i <= (n); i++) if (b[i] != c[i]) f[i] = 1; for (int i = (1); i <= (n); i++) for (auto j : e[i]) if (f[i] && f[j]) ch[i].push_back(j); int A = -1, B = -1; for (int i = (1); i <= (n); i++) if (ch[i].size() > 2) NO(); else if (ch[i].size() == 1) { if (A == -1) A = i; else if (B == -1) B = i; else NO(); } else if (ch[i].empty() && f[i]) NO(); if (B == -1) NO(); if (dis(B, s) < dis(B, t)) swap(A, B); b[t] = c[t] = 0; dfs_ch(A); vector<int> pos(n + 1, -1); int cs = (int)cid.size(); for (int i = (0); i <= (cs - 1); i++) pos[b[cid[i]]] = i; int d = -1; for (int i = (0); i <= (cs - 1); i++) { if (cid[i] == t) continue; int p0 = pos[c[cid[i]]], p1 = i; p0 -= p0 >= tp, p1 -= p1 >= tp; int di = (p1 - p0 + cs - 1) % (cs - 1); if (d != -1 && d != di) NO(); d = di; } int dst = dis(s, t); long long d1 = (long long)cs * d + dst, d2 = (long long)cs * (cs - 1) - d1; long long ans = dis(s0, s) + dis(t0, t) + min(d1, d2); cout << min(A, B) << " " << max(A, B) << " " << ans << endl; return 0; }
### Prompt Create a solution in cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f = ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 200005; int n, s0, t0, s, t, tp; vector<int> e[N], ch[N]; int a[N], b[N], c[N], f[N]; deque<int> id; int find(int *a, int v) { for (int i = (1); i <= (n); i++) if (a[i] == v) return i; return 0; } int check(int *a, int *b) { for (int i = (1); i <= (n); i++) if (a[i] != b[i]) return 0; return 1; } int fa[N], dep[N], anc[N][20]; void dfs(int x, int pre = 0, int d = 0) { anc[x][0] = fa[x] = pre, dep[x] = d; for (int i = (1); i <= (19); i++) anc[x][i] = anc[anc[x][i - 1]][i - 1]; for (auto y : e[x]) if (y != pre) dfs(y, x, d + 1); } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = (19); i >= (0); i--) if (dep[x] - (1 << i) >= dep[y]) x = anc[x][i]; if (x == y) return x; for (int i = (19); i >= (0); i--) if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i]; return fa[x]; } int dis(int x, int y) { return dep[x] + dep[y] - 2 * dep[LCA(x, y)]; } void getc() { s0 = find(a, 0), t0 = find(b, 0); dfs(t0); for (int i = (1); i <= (n); i++) c[i] = a[i]; for (int x = s0; x != t0; x = fa[x]) id.push_back(x), swap(c[x], c[fa[x]]); id.push_back(t0); if (check(b, c)) printf("0 %d\n", dep[s0]), exit(0); } void NO() { puts("-1"); exit(0); } vector<int> cid; void dfs_ch(int x, int pre = 0) { cid.push_back(x); if (x == t) tp = (int)cid.size() - 1; for (auto y : ch[x]) if (y != pre) dfs_ch(y, x); } int main() { n = read(); for (int i = (1); i <= (n); i++) a[i] = read(); int Test = a[1] == 3779; for (int i = (1); i <= (n); i++) b[i] = read(); for (int i = (1); i <= (n - 1); i++) { int x = read(), y = read(); e[x].push_back(y), e[y].push_back(x); } getc(); deque<int> ID = id; while ((int)id.size() >= 2 && b[id[0]] == c[id[0]]) id.pop_front(); while ((int)id.size() >= 2 && b[id[(int)id.size() - 2]] == c[id[(int)id.size() - 2]]) id.pop_back(); assert(!id.empty()); s = id.front(), t = id.back(); if (b[id[0]] != c[id[0]]) { for (auto i : id) f[i] = 1; } else { int x = -1; for (int i = (1); i <= (n); i++) if (b[i] != c[i]) if (x == -1 || dis(i, t0) < dis(x, t0)) x = i; assert(x != -1); for (auto y : e[x]) if (dis(y, t0) < dis(x, t0)) { f[s = t = y] = 1; break; } assert(s != 0); } for (int i = (1); i <= (n); i++) if (b[i] != c[i]) f[i] = 1; for (int i = (1); i <= (n); i++) for (auto j : e[i]) if (f[i] && f[j]) ch[i].push_back(j); int A = -1, B = -1; for (int i = (1); i <= (n); i++) if (ch[i].size() > 2) NO(); else if (ch[i].size() == 1) { if (A == -1) A = i; else if (B == -1) B = i; else NO(); } else if (ch[i].empty() && f[i]) NO(); if (B == -1) NO(); if (dis(B, s) < dis(B, t)) swap(A, B); b[t] = c[t] = 0; dfs_ch(A); vector<int> pos(n + 1, -1); int cs = (int)cid.size(); for (int i = (0); i <= (cs - 1); i++) pos[b[cid[i]]] = i; int d = -1; for (int i = (0); i <= (cs - 1); i++) { if (cid[i] == t) continue; int p0 = pos[c[cid[i]]], p1 = i; p0 -= p0 >= tp, p1 -= p1 >= tp; int di = (p1 - p0 + cs - 1) % (cs - 1); if (d != -1 && d != di) NO(); d = di; } int dst = dis(s, t); long long d1 = (long long)cs * d + dst, d2 = (long long)cs * (cs - 1) - d1; long long ans = dis(s0, s) + dis(t0, t) + min(d1, d2); cout << min(A, B) << " " << max(A, B) << " " << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; namespace SHENZHEBEI { static const int GYN = 2333333; char SZB[GYN], *SS = SZB, *TT = SZB; inline char gc() { if (SS == TT) { TT = (SS = SZB) + fread(SZB, 1, GYN, stdin); if (SS == TT) return '\n'; } return *SS++; } inline long long read() { long long x = 0, g = 1; char ch = gc(); for (; !isdigit(ch); ch = gc()) if (ch == '-') g = -1; for (; isdigit(ch); ch = gc()) x = x * 10 - 48 + ch; return x * g; } inline void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } inline char readchar() { char ch = gc(); for (; isspace(ch); ch = gc()) ; return ch; } inline long long readstr(char *s) { char ch = gc(); int cur = 0; for (; isspace(ch); ch = gc()) ; for (; !isspace(ch); ch = gc()) s[cur++] = ch; s[cur] = '\0'; return cur; } void Print(long long *a, int s, int t) { for (int i = (long long)(s); i <= (long long)(t); ++i) printf("%lld ", a[i]); } void Print(int *a, int s, int t) { for (int i = (long long)(s); i <= (long long)(t); ++i) printf("%d ", a[i]); } void Print(char *a, int s, int t) { for (int i = (long long)(s); i <= (long long)(t); ++i) putchar(a[i]); } void writeln(long long x) { write(x); puts(""); } void Min(long long &x, long long y) { x = x < y ? x : y; } void Max(long long &x, long long y) { x = x > y ? x : y; } } // namespace SHENZHEBEI using namespace SHENZHEBEI; const long long N = 400010; vector<long long> g[N]; vector<long long> lzh; long long dep[N], a[N], b[N], fa[N], vis[N], cqz, n, zyy, sum, best, Best, Rt, id1, id2, ans; void dfs(long long x) { for (int i = (long long)(0); i < (long long)(g[x].size()); ++i) { long long to = g[x][i]; if (to == fa[x]) continue; fa[to] = x; dep[to] = dep[x] + 1; dfs(to); } } long long lca(long long x, long long y) { for (; x != y; x = fa[x]) if (dep[x] < dep[y]) swap(x, y); return x; } bool fafa() { best = 0, Best = 0; for (int i = (long long)(1); i <= (long long)(n); ++i) if (a[i] != b[i]) best = dep[best] < dep[i] ? i : best; if (!best) return 1; for (long long i = best; vis[i] = 1, lzh.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; for (int i = (long long)(1); i <= (long long)(n); ++i) if (a[i] != b[i] && !vis[i]) Best = dep[Best] < dep[i] ? i : Best; if (Best) { reverse(lzh.begin(), lzh.end()); for (long long i = Best; vis[i] = 1, lzh.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; } else Best = fa[lzh.back()]; for (int i = (long long)(1); i <= (long long)(n); ++i) if (a[i] != b[i] && !vis[i]) return 0; Rt = lca(best, Best); if (lzh.size() != dep[best] + dep[Best] - 2 * dep[Rt]) return 0; return 1; } int main() { n = read(); for (int i = (long long)(1); i <= (long long)(n); ++i) a[i] = read(), id1 = a[i] ? id1 : i; for (int i = (long long)(1); i <= (long long)(n); ++i) b[i] = read(), id2 = b[i] ? id2 : i; for (int i = (long long)(1); i < (long long)(n); ++i) { long long a = read(), b = read(); g[a].push_back(b); g[b].push_back(a); } dep[0] = -1; dfs(id2); for (long long i = id1; i != id2; i = fa[i]) swap(a[i], a[fa[i]]); ans = dep[id1]; if (!fafa()) return puts("-1"), 0; if (!lzh.size()) return printf("0 %lld\n", ans), 0; zyy = 0, sum = lzh.size(); for (int i = (long long)(0); i < (long long)(sum); ++i) if (b[lzh[i]] == a[lzh[0]]) zyy = i; for (int i = (long long)(1); i < (long long)(sum); ++i) if (b[lzh[(i + zyy) % sum]] != a[lzh[i]]) return puts("-1"), 0; memset(vis, 0, sizeof vis); for (long long i = id1; i; i = fa[i]) vis[i] = 1; if (vis[lzh[0]] || vis[lzh.back()]) { for (int i = (long long)(0); i < (long long)(sum); ++i) if (!vis[lzh[i]]) { cqz = i; break; } ans += -cqz + ((cqz + zyy * (sum + 1)) < (abs((sum - zyy) * (sum + 1) - cqz)) ? (cqz + zyy * (sum + 1)) : (abs((sum - zyy) * (sum + 1) - cqz))); } else ans += ((zyy) < (sum - zyy) ? (zyy) : (sum - zyy)) * (sum + 1); for (; !vis[Rt]; Rt = fa[Rt]) ans += 2; if (best > Best) swap(best, Best); printf("%lld %lld %lld\n", best, Best, ans); }
### Prompt Create a solution in CPP for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; namespace SHENZHEBEI { static const int GYN = 2333333; char SZB[GYN], *SS = SZB, *TT = SZB; inline char gc() { if (SS == TT) { TT = (SS = SZB) + fread(SZB, 1, GYN, stdin); if (SS == TT) return '\n'; } return *SS++; } inline long long read() { long long x = 0, g = 1; char ch = gc(); for (; !isdigit(ch); ch = gc()) if (ch == '-') g = -1; for (; isdigit(ch); ch = gc()) x = x * 10 - 48 + ch; return x * g; } inline void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } inline char readchar() { char ch = gc(); for (; isspace(ch); ch = gc()) ; return ch; } inline long long readstr(char *s) { char ch = gc(); int cur = 0; for (; isspace(ch); ch = gc()) ; for (; !isspace(ch); ch = gc()) s[cur++] = ch; s[cur] = '\0'; return cur; } void Print(long long *a, int s, int t) { for (int i = (long long)(s); i <= (long long)(t); ++i) printf("%lld ", a[i]); } void Print(int *a, int s, int t) { for (int i = (long long)(s); i <= (long long)(t); ++i) printf("%d ", a[i]); } void Print(char *a, int s, int t) { for (int i = (long long)(s); i <= (long long)(t); ++i) putchar(a[i]); } void writeln(long long x) { write(x); puts(""); } void Min(long long &x, long long y) { x = x < y ? x : y; } void Max(long long &x, long long y) { x = x > y ? x : y; } } // namespace SHENZHEBEI using namespace SHENZHEBEI; const long long N = 400010; vector<long long> g[N]; vector<long long> lzh; long long dep[N], a[N], b[N], fa[N], vis[N], cqz, n, zyy, sum, best, Best, Rt, id1, id2, ans; void dfs(long long x) { for (int i = (long long)(0); i < (long long)(g[x].size()); ++i) { long long to = g[x][i]; if (to == fa[x]) continue; fa[to] = x; dep[to] = dep[x] + 1; dfs(to); } } long long lca(long long x, long long y) { for (; x != y; x = fa[x]) if (dep[x] < dep[y]) swap(x, y); return x; } bool fafa() { best = 0, Best = 0; for (int i = (long long)(1); i <= (long long)(n); ++i) if (a[i] != b[i]) best = dep[best] < dep[i] ? i : best; if (!best) return 1; for (long long i = best; vis[i] = 1, lzh.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; for (int i = (long long)(1); i <= (long long)(n); ++i) if (a[i] != b[i] && !vis[i]) Best = dep[Best] < dep[i] ? i : Best; if (Best) { reverse(lzh.begin(), lzh.end()); for (long long i = Best; vis[i] = 1, lzh.push_back(i), a[fa[i]] != b[fa[i]]; i = fa[i]) ; } else Best = fa[lzh.back()]; for (int i = (long long)(1); i <= (long long)(n); ++i) if (a[i] != b[i] && !vis[i]) return 0; Rt = lca(best, Best); if (lzh.size() != dep[best] + dep[Best] - 2 * dep[Rt]) return 0; return 1; } int main() { n = read(); for (int i = (long long)(1); i <= (long long)(n); ++i) a[i] = read(), id1 = a[i] ? id1 : i; for (int i = (long long)(1); i <= (long long)(n); ++i) b[i] = read(), id2 = b[i] ? id2 : i; for (int i = (long long)(1); i < (long long)(n); ++i) { long long a = read(), b = read(); g[a].push_back(b); g[b].push_back(a); } dep[0] = -1; dfs(id2); for (long long i = id1; i != id2; i = fa[i]) swap(a[i], a[fa[i]]); ans = dep[id1]; if (!fafa()) return puts("-1"), 0; if (!lzh.size()) return printf("0 %lld\n", ans), 0; zyy = 0, sum = lzh.size(); for (int i = (long long)(0); i < (long long)(sum); ++i) if (b[lzh[i]] == a[lzh[0]]) zyy = i; for (int i = (long long)(1); i < (long long)(sum); ++i) if (b[lzh[(i + zyy) % sum]] != a[lzh[i]]) return puts("-1"), 0; memset(vis, 0, sizeof vis); for (long long i = id1; i; i = fa[i]) vis[i] = 1; if (vis[lzh[0]] || vis[lzh.back()]) { for (int i = (long long)(0); i < (long long)(sum); ++i) if (!vis[lzh[i]]) { cqz = i; break; } ans += -cqz + ((cqz + zyy * (sum + 1)) < (abs((sum - zyy) * (sum + 1) - cqz)) ? (cqz + zyy * (sum + 1)) : (abs((sum - zyy) * (sum + 1) - cqz))); } else ans += ((zyy) < (sum - zyy) ? (zyy) : (sum - zyy)) * (sum + 1); for (; !vis[Rt]; Rt = fa[Rt]) ans += 2; if (best > Best) swap(best, Best); printf("%lld %lld %lld\n", best, Best, ans); } ```
#include <bits/stdc++.h> using namespace std; const int WZP = 6666666; char LZH[WZP], *SSS = LZH, *TTT = LZH; inline char gc() { if (SSS == TTT) { TTT = (SSS = LZH) + fread(LZH, 1, WZP, stdin); if (SSS == TTT) return EOF; } return *SSS++; } inline int read01() { char s = gc(); for (; s < '0' || s > '1'; s = gc()) ; return s - '0'; } inline int read() { char s = gc(); int x = 0; for (; s < '0' || s > '9'; s = gc()) ; for (; s >= '0' && s <= '9'; s = gc()) x = x * 10 - 48 + s; return x; } const int N = 200005; struct edge { int to, next; } e[N * 2]; int head[N], tot; int dep[N], dfn[N], ed[N]; int fa[N][19], a[N], b[N]; int n, spe1, spe2, A[N], B[N]; void add(int x, int y) { e[++tot] = (edge){y, head[x]}; head[x] = tot; } void dfs(int x) { dep[x] = dep[fa[x][0]] + 1; dfn[x] = ++*dfn; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa[x][0]) { fa[e[i].to][0] = x; dfs(e[i].to); } ed[x] = *dfn; } bool insub(int x, int y) { return dfn[x] <= dfn[y] && ed[y] <= ed[x]; } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); int tmp = dep[x] - dep[y]; for (int i = (int)(0); i <= (int)(18); i++) if (tmp & (1 << i)) x = fa[x][i]; for (int i = (int)(18); i >= (int)(0); i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return x == y ? x : fa[x][0]; } pair<int, int> merge(const pair<int, int> &a, int x) { if (a.first == -1) return pair<int, int>(-1, -1); if (a.first == 0) return pair<int, int>(x, x); static int c[5], L; c[0] = a.first; c[1] = a.second; c[2] = x; L = LCA(c[0], c[1]); if (insub(L, c[2]) && (insub(c[2], c[0]) || insub(c[2], c[1]))) return pair<int, int>(c[0], c[1]); L = LCA(c[0], c[2]); if (insub(L, c[1]) && (insub(c[1], c[0]) || insub(c[1], c[2]))) return pair<int, int>(c[0], c[2]); L = LCA(c[1], c[2]); if (insub(L, c[0]) && (insub(c[0], c[1]) || insub(c[0], c[2]))) return pair<int, int>(c[1], c[2]); return pair<int, int>(-1, -1); } long long solve(int x, int y, int L, int *a) { int l = 1, r = dep[x] + dep[y] - 2 * dep[L], len = r, at = 1; for (; x != L; x = fa[x][0], l++) A[l] = a[x], B[l] = b[x]; for (; y != L; y = fa[y][0], r--) A[r] = a[y], B[r] = b[y]; for (int i = (int)(1); i <= (int)(len); i++) if (A[i]) for (; A[1] != B[at]; at++) ; for (int i = 1; i <= len; i++) if (A[i] != B[(i + at - 2) % len + 1]) return 1ll << 60; return 1ll * min(at - 1, len + 1 - at) * (len + 1); } int cnt, aa[N]; bool dfs(int x, int fa, int spe) { if (x == spe) return 1; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa) if (dfs(e[i].to, x, spe)) { cnt++; swap(aa[x], aa[e[i].to]); return 1; } return 0; } void flip(int p1, int p2) { dfs(p2, 0, p1); } bool checkSAME(int *a, int *b) { for (int i = (int)(1); i <= (int)(n); i++) if (a[i] != b[i]) return 0; return 1; } int tp; int main() { n = read(); for (int i = (int)(1); i <= (int)(n); i++) a[i] = read(), spe1 = (a[i] == 0 ? i : spe1); for (int i = (int)(1); i <= (int)(n); i++) b[i] = read(), spe2 = (b[i] == 0 ? i : spe2); for (int i = (int)(1); i <= (int)(n - 1); i++) { int x = read(), y = read(); add(x, y); add(y, x); } memcpy(aa, a, sizeof(aa)); dfs(spe2); flip(spe1, spe2); if (checkSAME(aa, b)) return printf("0 %d\n", cnt), 0; for (int i = (int)(1); i <= (int)(18); i++) for (int j = (int)(1); j <= (int)(n); j++) fa[j][i] = fa[fa[j][i - 1]][i - 1]; pair<int, int> tmp(0, 0); for (int i = (int)(1); i <= (int)(n); i++) if (aa[i] != b[i]) tmp = merge(tmp, i); if (tmp.first == -1) return puts("-1"), 0; if (dep[tmp.first] > dep[tmp.second]) swap(tmp.first, tmp.second); if (insub(tmp.first, tmp.second)) tmp.first = fa[tmp.first][0]; long long ans = 1ll << 60; int L1 = LCA(tmp.first, tmp.second); cnt = 0; memcpy(aa, a, sizeof(aa)); flip(spe1, tmp.first); swap(aa[tmp.first], aa[tmp.second]); cnt++; flip(tmp.second, spe2); ans = min(ans, cnt + solve(tmp.first, tmp.second, L1, aa)); cnt = 0; memcpy(aa, a, sizeof(aa)); flip(spe1, tmp.second); swap(aa[tmp.second], aa[tmp.first]); cnt++; flip(tmp.first, spe2); ans = min(ans, cnt + solve(tmp.first, tmp.second, L1, aa)); if (ans >= 1ll << 50) return puts("-1"), 0; if (tmp.first > tmp.second) swap(tmp.first, tmp.second); printf("%d %d ", tmp.first, tmp.second); printf("%lld\n", ans); }
### Prompt Please provide a CPP coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int WZP = 6666666; char LZH[WZP], *SSS = LZH, *TTT = LZH; inline char gc() { if (SSS == TTT) { TTT = (SSS = LZH) + fread(LZH, 1, WZP, stdin); if (SSS == TTT) return EOF; } return *SSS++; } inline int read01() { char s = gc(); for (; s < '0' || s > '1'; s = gc()) ; return s - '0'; } inline int read() { char s = gc(); int x = 0; for (; s < '0' || s > '9'; s = gc()) ; for (; s >= '0' && s <= '9'; s = gc()) x = x * 10 - 48 + s; return x; } const int N = 200005; struct edge { int to, next; } e[N * 2]; int head[N], tot; int dep[N], dfn[N], ed[N]; int fa[N][19], a[N], b[N]; int n, spe1, spe2, A[N], B[N]; void add(int x, int y) { e[++tot] = (edge){y, head[x]}; head[x] = tot; } void dfs(int x) { dep[x] = dep[fa[x][0]] + 1; dfn[x] = ++*dfn; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa[x][0]) { fa[e[i].to][0] = x; dfs(e[i].to); } ed[x] = *dfn; } bool insub(int x, int y) { return dfn[x] <= dfn[y] && ed[y] <= ed[x]; } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); int tmp = dep[x] - dep[y]; for (int i = (int)(0); i <= (int)(18); i++) if (tmp & (1 << i)) x = fa[x][i]; for (int i = (int)(18); i >= (int)(0); i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return x == y ? x : fa[x][0]; } pair<int, int> merge(const pair<int, int> &a, int x) { if (a.first == -1) return pair<int, int>(-1, -1); if (a.first == 0) return pair<int, int>(x, x); static int c[5], L; c[0] = a.first; c[1] = a.second; c[2] = x; L = LCA(c[0], c[1]); if (insub(L, c[2]) && (insub(c[2], c[0]) || insub(c[2], c[1]))) return pair<int, int>(c[0], c[1]); L = LCA(c[0], c[2]); if (insub(L, c[1]) && (insub(c[1], c[0]) || insub(c[1], c[2]))) return pair<int, int>(c[0], c[2]); L = LCA(c[1], c[2]); if (insub(L, c[0]) && (insub(c[0], c[1]) || insub(c[0], c[2]))) return pair<int, int>(c[1], c[2]); return pair<int, int>(-1, -1); } long long solve(int x, int y, int L, int *a) { int l = 1, r = dep[x] + dep[y] - 2 * dep[L], len = r, at = 1; for (; x != L; x = fa[x][0], l++) A[l] = a[x], B[l] = b[x]; for (; y != L; y = fa[y][0], r--) A[r] = a[y], B[r] = b[y]; for (int i = (int)(1); i <= (int)(len); i++) if (A[i]) for (; A[1] != B[at]; at++) ; for (int i = 1; i <= len; i++) if (A[i] != B[(i + at - 2) % len + 1]) return 1ll << 60; return 1ll * min(at - 1, len + 1 - at) * (len + 1); } int cnt, aa[N]; bool dfs(int x, int fa, int spe) { if (x == spe) return 1; for (int i = head[x]; i; i = e[i].next) if (e[i].to != fa) if (dfs(e[i].to, x, spe)) { cnt++; swap(aa[x], aa[e[i].to]); return 1; } return 0; } void flip(int p1, int p2) { dfs(p2, 0, p1); } bool checkSAME(int *a, int *b) { for (int i = (int)(1); i <= (int)(n); i++) if (a[i] != b[i]) return 0; return 1; } int tp; int main() { n = read(); for (int i = (int)(1); i <= (int)(n); i++) a[i] = read(), spe1 = (a[i] == 0 ? i : spe1); for (int i = (int)(1); i <= (int)(n); i++) b[i] = read(), spe2 = (b[i] == 0 ? i : spe2); for (int i = (int)(1); i <= (int)(n - 1); i++) { int x = read(), y = read(); add(x, y); add(y, x); } memcpy(aa, a, sizeof(aa)); dfs(spe2); flip(spe1, spe2); if (checkSAME(aa, b)) return printf("0 %d\n", cnt), 0; for (int i = (int)(1); i <= (int)(18); i++) for (int j = (int)(1); j <= (int)(n); j++) fa[j][i] = fa[fa[j][i - 1]][i - 1]; pair<int, int> tmp(0, 0); for (int i = (int)(1); i <= (int)(n); i++) if (aa[i] != b[i]) tmp = merge(tmp, i); if (tmp.first == -1) return puts("-1"), 0; if (dep[tmp.first] > dep[tmp.second]) swap(tmp.first, tmp.second); if (insub(tmp.first, tmp.second)) tmp.first = fa[tmp.first][0]; long long ans = 1ll << 60; int L1 = LCA(tmp.first, tmp.second); cnt = 0; memcpy(aa, a, sizeof(aa)); flip(spe1, tmp.first); swap(aa[tmp.first], aa[tmp.second]); cnt++; flip(tmp.second, spe2); ans = min(ans, cnt + solve(tmp.first, tmp.second, L1, aa)); cnt = 0; memcpy(aa, a, sizeof(aa)); flip(spe1, tmp.second); swap(aa[tmp.second], aa[tmp.first]); cnt++; flip(tmp.first, spe2); ans = min(ans, cnt + solve(tmp.first, tmp.second, L1, aa)); if (ans >= 1ll << 50) return puts("-1"), 0; if (tmp.first > tmp.second) swap(tmp.first, tmp.second); printf("%d %d ", tmp.first, tmp.second); printf("%lld\n", ans); } ```
#include <bits/stdc++.h> using namespace std; const int N = 200200; int n, u, v, S, T, x, y, X, Y, Q, L, p, fl; long long ans; int hd[N], fa[N], vi[N], d[N], a[N], b[N], q[N]; struct edge { int n, v; } e[N << 1]; void add(int u, int v) { e[++fl] = {hd[u], v}; hd[u] = fl; } void dfs(int u) { for (int i = hd[u], v; v = e[i].v, i; i = e[i].n) if (v != fa[u]) fa[v] = u, d[v] = d[u] + 1, dfs(v); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), S = a[i] ? S : i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), T = b[i] ? T : i; for (int i = 2; i <= n; i++) scanf("%d%d", &u, &v), add(u, v), add(v, u); dfs(T); ans = d[S]; for (u = S; u; u = fa[u]) a[u] = a[fa[u]]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[x] < d[i]) x = i; X = x; for (; a[x] != b[x]; x = fa[x]) vi[x] = 1, q[Q++] = x; if (!X) return cout << 0 << ' ' << ans << '\n', 0; reverse(q, q + Q); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[y] < d[i]) y = i; Y = y ? y : x; for (; a[y] != b[y]; y = fa[y]) vi[y] = 1, q[Q++] = y; if (y && x != y) return puts("-1"), 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i]) return puts("-1"), 0; for (int i = 1; i <= n; i++) vi[i] = 0; for (u = S; u; u = fa[u]) vi[u] = 1; if (!vi[q[0]]) reverse(q, q + Q); for (int i = 0; i <= Q - 1; i++) if (a[q[0]] == b[q[i]]) p = i; for (int i = 0; i <= Q - 1; i++) if (a[q[i]] != b[q[(i + p) % Q]]) return puts("-1"), 0; for (int i = 0; i <= Q - 1; i++) if (!vi[q[i]]) { L = i; break; } ans += min(1ll * (Q + 1) * p, 1ll * (Q + 1) * (Q - p) - 2 * L); for (; !vi[x]; x = fa[x]) ans += 2; if (X > Y) swap(X, Y); cout << X << ' ' << Y << ' ' << ans << '\n'; }
### Prompt In cpp, your task is to solve the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200200; int n, u, v, S, T, x, y, X, Y, Q, L, p, fl; long long ans; int hd[N], fa[N], vi[N], d[N], a[N], b[N], q[N]; struct edge { int n, v; } e[N << 1]; void add(int u, int v) { e[++fl] = {hd[u], v}; hd[u] = fl; } void dfs(int u) { for (int i = hd[u], v; v = e[i].v, i; i = e[i].n) if (v != fa[u]) fa[v] = u, d[v] = d[u] + 1, dfs(v); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), S = a[i] ? S : i; for (int i = 1; i <= n; i++) scanf("%d", &b[i]), T = b[i] ? T : i; for (int i = 2; i <= n; i++) scanf("%d%d", &u, &v), add(u, v), add(v, u); dfs(T); ans = d[S]; for (u = S; u; u = fa[u]) a[u] = a[fa[u]]; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[x] < d[i]) x = i; X = x; for (; a[x] != b[x]; x = fa[x]) vi[x] = 1, q[Q++] = x; if (!X) return cout << 0 << ' ' << ans << '\n', 0; reverse(q, q + Q); for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i] && d[y] < d[i]) y = i; Y = y ? y : x; for (; a[y] != b[y]; y = fa[y]) vi[y] = 1, q[Q++] = y; if (y && x != y) return puts("-1"), 0; for (int i = 1; i <= n; i++) if (a[i] != b[i] && !vi[i]) return puts("-1"), 0; for (int i = 1; i <= n; i++) vi[i] = 0; for (u = S; u; u = fa[u]) vi[u] = 1; if (!vi[q[0]]) reverse(q, q + Q); for (int i = 0; i <= Q - 1; i++) if (a[q[0]] == b[q[i]]) p = i; for (int i = 0; i <= Q - 1; i++) if (a[q[i]] != b[q[(i + p) % Q]]) return puts("-1"), 0; for (int i = 0; i <= Q - 1; i++) if (!vi[q[i]]) { L = i; break; } ans += min(1ll * (Q + 1) * p, 1ll * (Q + 1) * (Q - p) - 2 * L); for (; !vi[x]; x = fa[x]) ans += 2; if (X > Y) swap(X, Y); cout << X << ' ' << Y << ' ' << ans << '\n'; } ```
#include <bits/stdc++.h> using namespace std; template <typename T, typename S> inline bool upmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; } template <typename T, typename S> inline bool upmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; } template <typename N, typename PN> inline N flo(N a, PN b) { return a >= 0 ? a / b : -((-a - 1) / b) - 1; } template <typename N, typename PN> inline N cei(N a, PN b) { return a > 0 ? (a - 1) / b + 1 : -(-a / b); } template <typename N> N gcd(N a, N b) { return b ? gcd(b, a % b) : a; } inline void gn(long long& x) { int sg = 1; char c; while (((c = getchar()) < '0' || c > '9') && c != '-') ; c == '-' ? (sg = -1, x = 0) : (x = c - '0'); while ((c = getchar()) >= '0' && c <= '9') x = x * 10 + c - '0'; x *= sg; } inline void gn(int& x) { long long t; gn(t); x = t; } inline void gn(unsigned long long& x) { long long t; gn(t); x = t; } inline void gn(double& x) { double t; scanf("%lf", &t); x = t; } inline void gn(long double& x) { double t; scanf("%lf", &t); x = t; } inline long long sqr(long long a) { return a * a; } inline double sqrf(double a) { return a * a; } const int inf = 0x3f3f3f3f; const double eps = 1e-6; int mo = 1000000007; int qp(int a, long long b) { int n = 1; do { if (b & 1) n = 1ll * n * a % mo; a = 1ll * a * a % mo; } while (b >>= 1); return n; } const int TREE_MAXV = 200000 + 5; struct edge { int v, next; } e[TREE_MAXV * 2]; int g[TREE_MAXV], etot; int qu[TREE_MAXV], pre[TREE_MAXV], h[TREE_MAXV]; int n; void ae(int u, int v) { e[etot].v = v; e[etot].next = g[u]; g[u] = etot++; } void bfs(int rt) { int p = 0, q = 0; pre[rt] = 0; h[rt] = 0; qu[q++] = rt; while (p != q) { int u = qu[p++]; for (int i = g[u]; ~i; i = e[i].next) if (e[i].v != pre[u]) { pre[e[i].v] = u; h[e[i].v] = h[u] + 1; qu[q++] = e[i].v; } } } void tree_init() { static bool ini = 0; if (!ini) { ini = 1; memset(g, -1, sizeof(g)); } else { for (int i = 0; i <= n; i++) g[i] = -1; } etot = 0; } void readedge() { for (int i = 1; i < n; i++) { int x, y; gn(x); gn(y); ae(x, y); ae(y, x); } } int ai[222222], bi[222222]; int a0, b0; int aii[222222]; int dif[222222]; int des[222222]; int lis[222222]; int ltot = 0; int s1[422222], s2[422222]; int on[222222]; int disb, disa; int lcapos; long long gao(int ia, int ib, int ia0, int ib0, int ltot) { long long t = 0; ia--, ib--, ia0--, ib0--; while (ia0 != ib0) { if ((ia0 + 1) % ltot == ia) ia = ia0; ia0 = (ia0 + 1) % ltot; t++; } while (ia != ib) { t += ltot; ia = (ia + ltot - 1) % ltot; if (ia == ia0) ia = (ia + ltot - 1) % ltot; } return t; } int main() { tree_init(); gn(n); for (int i = (1), _ed = (n + 1); i < _ed; i++) { gn(ai[i]); if (ai[i] == 0) a0 = i; aii[i] = ai[i]; } for (int i = (1), _ed = (n + 1); i < _ed; i++) { gn(bi[i]); if (bi[i] == 0) b0 = i; } readedge(); bfs(b0); int u = a0; int hi = 0; while (u != b0) { hi++; swap(aii[u], aii[pre[u]]); u = pre[u]; } int bo = 0; for (int i = (1), _ed = (n + 1); i < _ed; i++) if (aii[i] != bi[i]) bo++, dif[i] = 1; if (bo == 0) { printf("%d %d\n", 0, hi); return 0; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i]) { u = i; break; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] && h[i] > h[u]) u = i; int w = u; while (w) { des[w] ^= 1; w = pre[w]; } int v; for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] != des[i]) { v = i; break; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] != des[i] && h[i] > h[v]) { v = i; } w = v; while (w) { des[w] ^= 1; w = pre[w]; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] != des[i]) { printf("-1\n"); return 0; } bfs(u); w = v; int lca; while (w) { if (dif[w]) lis[++ltot] = w; else lca = w, lcapos = ltot; w = pre[w]; } bfs(b0); disb = h[lca]; w = u; while (w) { des[w] ^= 1; w = pre[w]; } w = v; while (w) { des[w] ^= 1; w = pre[w]; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) { s1[i] = aii[lis[i]]; s2[i] = bi[lis[i]]; } int st = 0; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s1[i] == s2[1]) { st = i; break; } if (!st) { printf("-1\n"); return 0; } s1[0] = s1[ltot]; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s1[(st - 1 + i) % ltot] != s2[i]) { printf("-1\n"); return 0; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) { on[lis[i]] = 1; } on[lca] = 1; bfs(a0); int au = lca; for (int i = (1), _ed = (n + 1); i < _ed; i++) if (on[i] && h[i] < h[au]) au = i; disa = h[au]; for (int i = ltot; i > lcapos; i--) lis[i + 1] = lis[i]; lis[lcapos + 1] = lca; ltot++; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) s1[i] = lis[i] == au ? 0 : ai[lis[i]], s2[i] = lis[i] == lca ? 0 : bi[lis[i]]; long long ans = disa + disb; int c, ia, ib; int ia0, ib0; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s1[i]) { c = s1[i]; ia = i; break; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s2[i] == c) { ib = i; break; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) { if (s1[i] == 0) ia0 = i; if (s2[i] == 0) ib0 = i; } ans += min( gao(ia, ib, ia0, ib0, ltot), gao(ltot - ia + 1, ltot - ib + 1, ltot - ia0 + 1, ltot - ib0 + 1, ltot)); cout << min(u, v) << " " << max(u, v) << " " << ans << endl; return 0; }
### Prompt Generate a Cpp solution to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T, typename S> inline bool upmin(T& a, const S& b) { return a > b ? a = b, 1 : 0; } template <typename T, typename S> inline bool upmax(T& a, const S& b) { return a < b ? a = b, 1 : 0; } template <typename N, typename PN> inline N flo(N a, PN b) { return a >= 0 ? a / b : -((-a - 1) / b) - 1; } template <typename N, typename PN> inline N cei(N a, PN b) { return a > 0 ? (a - 1) / b + 1 : -(-a / b); } template <typename N> N gcd(N a, N b) { return b ? gcd(b, a % b) : a; } inline void gn(long long& x) { int sg = 1; char c; while (((c = getchar()) < '0' || c > '9') && c != '-') ; c == '-' ? (sg = -1, x = 0) : (x = c - '0'); while ((c = getchar()) >= '0' && c <= '9') x = x * 10 + c - '0'; x *= sg; } inline void gn(int& x) { long long t; gn(t); x = t; } inline void gn(unsigned long long& x) { long long t; gn(t); x = t; } inline void gn(double& x) { double t; scanf("%lf", &t); x = t; } inline void gn(long double& x) { double t; scanf("%lf", &t); x = t; } inline long long sqr(long long a) { return a * a; } inline double sqrf(double a) { return a * a; } const int inf = 0x3f3f3f3f; const double eps = 1e-6; int mo = 1000000007; int qp(int a, long long b) { int n = 1; do { if (b & 1) n = 1ll * n * a % mo; a = 1ll * a * a % mo; } while (b >>= 1); return n; } const int TREE_MAXV = 200000 + 5; struct edge { int v, next; } e[TREE_MAXV * 2]; int g[TREE_MAXV], etot; int qu[TREE_MAXV], pre[TREE_MAXV], h[TREE_MAXV]; int n; void ae(int u, int v) { e[etot].v = v; e[etot].next = g[u]; g[u] = etot++; } void bfs(int rt) { int p = 0, q = 0; pre[rt] = 0; h[rt] = 0; qu[q++] = rt; while (p != q) { int u = qu[p++]; for (int i = g[u]; ~i; i = e[i].next) if (e[i].v != pre[u]) { pre[e[i].v] = u; h[e[i].v] = h[u] + 1; qu[q++] = e[i].v; } } } void tree_init() { static bool ini = 0; if (!ini) { ini = 1; memset(g, -1, sizeof(g)); } else { for (int i = 0; i <= n; i++) g[i] = -1; } etot = 0; } void readedge() { for (int i = 1; i < n; i++) { int x, y; gn(x); gn(y); ae(x, y); ae(y, x); } } int ai[222222], bi[222222]; int a0, b0; int aii[222222]; int dif[222222]; int des[222222]; int lis[222222]; int ltot = 0; int s1[422222], s2[422222]; int on[222222]; int disb, disa; int lcapos; long long gao(int ia, int ib, int ia0, int ib0, int ltot) { long long t = 0; ia--, ib--, ia0--, ib0--; while (ia0 != ib0) { if ((ia0 + 1) % ltot == ia) ia = ia0; ia0 = (ia0 + 1) % ltot; t++; } while (ia != ib) { t += ltot; ia = (ia + ltot - 1) % ltot; if (ia == ia0) ia = (ia + ltot - 1) % ltot; } return t; } int main() { tree_init(); gn(n); for (int i = (1), _ed = (n + 1); i < _ed; i++) { gn(ai[i]); if (ai[i] == 0) a0 = i; aii[i] = ai[i]; } for (int i = (1), _ed = (n + 1); i < _ed; i++) { gn(bi[i]); if (bi[i] == 0) b0 = i; } readedge(); bfs(b0); int u = a0; int hi = 0; while (u != b0) { hi++; swap(aii[u], aii[pre[u]]); u = pre[u]; } int bo = 0; for (int i = (1), _ed = (n + 1); i < _ed; i++) if (aii[i] != bi[i]) bo++, dif[i] = 1; if (bo == 0) { printf("%d %d\n", 0, hi); return 0; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i]) { u = i; break; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] && h[i] > h[u]) u = i; int w = u; while (w) { des[w] ^= 1; w = pre[w]; } int v; for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] != des[i]) { v = i; break; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] != des[i] && h[i] > h[v]) { v = i; } w = v; while (w) { des[w] ^= 1; w = pre[w]; } for (int i = (1), _ed = (n + 1); i < _ed; i++) if (dif[i] != des[i]) { printf("-1\n"); return 0; } bfs(u); w = v; int lca; while (w) { if (dif[w]) lis[++ltot] = w; else lca = w, lcapos = ltot; w = pre[w]; } bfs(b0); disb = h[lca]; w = u; while (w) { des[w] ^= 1; w = pre[w]; } w = v; while (w) { des[w] ^= 1; w = pre[w]; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) { s1[i] = aii[lis[i]]; s2[i] = bi[lis[i]]; } int st = 0; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s1[i] == s2[1]) { st = i; break; } if (!st) { printf("-1\n"); return 0; } s1[0] = s1[ltot]; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s1[(st - 1 + i) % ltot] != s2[i]) { printf("-1\n"); return 0; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) { on[lis[i]] = 1; } on[lca] = 1; bfs(a0); int au = lca; for (int i = (1), _ed = (n + 1); i < _ed; i++) if (on[i] && h[i] < h[au]) au = i; disa = h[au]; for (int i = ltot; i > lcapos; i--) lis[i + 1] = lis[i]; lis[lcapos + 1] = lca; ltot++; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) s1[i] = lis[i] == au ? 0 : ai[lis[i]], s2[i] = lis[i] == lca ? 0 : bi[lis[i]]; long long ans = disa + disb; int c, ia, ib; int ia0, ib0; for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s1[i]) { c = s1[i]; ia = i; break; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) if (s2[i] == c) { ib = i; break; } for (int i = (1), _ed = (ltot + 1); i < _ed; i++) { if (s1[i] == 0) ia0 = i; if (s2[i] == 0) ib0 = i; } ans += min( gao(ia, ib, ia0, ib0, ltot), gao(ltot - ia + 1, ltot - ib + 1, ltot - ia0 + 1, ltot - ib0 + 1, ltot)); cout << min(u, v) << " " << max(u, v) << " " << ans << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int MAXN = 200 * 1000 + 5; int a[MAXN], b[MAXN], p[MAXN]; char onCycle[MAXN]; vector<int> g[MAXN]; void dfs(int v) { for (size_t i = 0; i < g[v].size(); i++) if (g[v][i] != p[v]) { p[g[v][i]] = v; dfs(g[v][i]); } } long long solve(vector<int> cycle, vector<int> a, vector<int> b) { size_t s = 0; while (a[s]) s++; long long res = 0; while (b[s]) { size_t nxt = (s + 1) % cycle.size(); swap(a[s], a[nxt]); s = nxt; res++; } a.erase(a.begin() + s); b.erase(b.begin() + s); int sh = 0; while (b[sh] != a[0]) sh++; res += (long long)min(sh, (int)a.size() - sh) * (long long)cycle.size(); rotate(b.begin(), b.begin() + sh, b.end()); if (a != b) return -1; return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; for (int i = 0; i < n - 1; i++) { int v, u; cin >> v >> u; v--; u--; g[v].push_back(u); g[u].push_back(v); } int s = -1, t = -1; for (int i = 0; i < n; i++) { if (!a[i]) s = i; if (!b[i]) t = i; } p[t] = -1; dfs(t); vector<pair<int, int> > st; while (s != t) { st.push_back(make_pair(s, p[s])); swap(a[s], a[p[s]]); s = p[s]; } for (int i = 0; i < n; i++) if (a[i] != b[i]) { onCycle[i] = true; onCycle[p[i]] = true; } vector<int> leaves; for (int i = 0; i < n; i++) if (onCycle[i]) { int deg = 0; for (size_t j = 0; j < g[i].size(); j++) if (onCycle[g[i][j]]) deg++; if (deg != 1 && deg != 2) { cout << -1 << '\n'; return 0; } if (deg == 1) leaves.push_back(i); } if (leaves.size() > 2) { cout << -1 << '\n'; return 0; } if (leaves.empty()) { cout << 0 << ' ' << st.size() << '\n'; return 0; } if (leaves[0] > leaves[1]) swap(leaves[0], leaves[1]); vector<int> cycle; cycle.push_back(leaves[0]); while (cycle.back() != leaves[1]) { int v = cycle.back(); for (size_t i = 0; i < g[v].size(); i++) if (onCycle[g[v][i]] && (cycle.size() == 1 || cycle[cycle.size() - 2] != g[v][i])) { cycle.push_back(g[v][i]); break; } } while (!st.empty()) { int v = st.back().first, u = st.back().second; swap(a[v], a[u]); st.pop_back(); } for (int i = 0; i < n; i++) if (!a[i]) s = i; int w = -1; for (int i = 0; i < n; i++) if (onCycle[i] && (p[i] == -1 || !onCycle[p[i]])) w = i; p[w] = -1; dfs(w); long long ans = 0; while (t != w) { swap(b[t], b[p[t]]); t = p[t]; ans++; } p[s] = -1; dfs(s); w = -1; for (int i = 0; i < n; i++) if (onCycle[i] && (p[i] == -1 || !onCycle[p[i]])) w = i; p[w] = -1; dfs(w); while (s != w) { swap(a[s], a[p[s]]); s = p[s]; ans++; } vector<int> ca(cycle.size()), cb(cycle.size()); for (size_t i = 0; i < cycle.size(); i++) { ca[i] = a[cycle[i]]; cb[i] = b[cycle[i]]; } long long ans0 = solve(cycle, ca, cb); reverse(cycle.begin(), cycle.end()); reverse(ca.begin(), ca.end()); reverse(cb.begin(), cb.end()); long long ans1 = solve(cycle, ca, cb); if (ans0 == -1) { if (ans1 == -1) ans = -1; else ans += ans1; } else { if (ans1 == -1) ans += ans0; else ans += min(ans0, ans1); } if (ans == -1) cout << -1 << '\n'; else cout << leaves[0] + 1 << ' ' << leaves[1] + 1 << ' ' << ans << '\n'; return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 200 * 1000 + 5; int a[MAXN], b[MAXN], p[MAXN]; char onCycle[MAXN]; vector<int> g[MAXN]; void dfs(int v) { for (size_t i = 0; i < g[v].size(); i++) if (g[v][i] != p[v]) { p[g[v][i]] = v; dfs(g[v][i]); } } long long solve(vector<int> cycle, vector<int> a, vector<int> b) { size_t s = 0; while (a[s]) s++; long long res = 0; while (b[s]) { size_t nxt = (s + 1) % cycle.size(); swap(a[s], a[nxt]); s = nxt; res++; } a.erase(a.begin() + s); b.erase(b.begin() + s); int sh = 0; while (b[sh] != a[0]) sh++; res += (long long)min(sh, (int)a.size() - sh) * (long long)cycle.size(); rotate(b.begin(), b.begin() + sh, b.end()); if (a != b) return -1; return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; for (int i = 0; i < n - 1; i++) { int v, u; cin >> v >> u; v--; u--; g[v].push_back(u); g[u].push_back(v); } int s = -1, t = -1; for (int i = 0; i < n; i++) { if (!a[i]) s = i; if (!b[i]) t = i; } p[t] = -1; dfs(t); vector<pair<int, int> > st; while (s != t) { st.push_back(make_pair(s, p[s])); swap(a[s], a[p[s]]); s = p[s]; } for (int i = 0; i < n; i++) if (a[i] != b[i]) { onCycle[i] = true; onCycle[p[i]] = true; } vector<int> leaves; for (int i = 0; i < n; i++) if (onCycle[i]) { int deg = 0; for (size_t j = 0; j < g[i].size(); j++) if (onCycle[g[i][j]]) deg++; if (deg != 1 && deg != 2) { cout << -1 << '\n'; return 0; } if (deg == 1) leaves.push_back(i); } if (leaves.size() > 2) { cout << -1 << '\n'; return 0; } if (leaves.empty()) { cout << 0 << ' ' << st.size() << '\n'; return 0; } if (leaves[0] > leaves[1]) swap(leaves[0], leaves[1]); vector<int> cycle; cycle.push_back(leaves[0]); while (cycle.back() != leaves[1]) { int v = cycle.back(); for (size_t i = 0; i < g[v].size(); i++) if (onCycle[g[v][i]] && (cycle.size() == 1 || cycle[cycle.size() - 2] != g[v][i])) { cycle.push_back(g[v][i]); break; } } while (!st.empty()) { int v = st.back().first, u = st.back().second; swap(a[v], a[u]); st.pop_back(); } for (int i = 0; i < n; i++) if (!a[i]) s = i; int w = -1; for (int i = 0; i < n; i++) if (onCycle[i] && (p[i] == -1 || !onCycle[p[i]])) w = i; p[w] = -1; dfs(w); long long ans = 0; while (t != w) { swap(b[t], b[p[t]]); t = p[t]; ans++; } p[s] = -1; dfs(s); w = -1; for (int i = 0; i < n; i++) if (onCycle[i] && (p[i] == -1 || !onCycle[p[i]])) w = i; p[w] = -1; dfs(w); while (s != w) { swap(a[s], a[p[s]]); s = p[s]; ans++; } vector<int> ca(cycle.size()), cb(cycle.size()); for (size_t i = 0; i < cycle.size(); i++) { ca[i] = a[cycle[i]]; cb[i] = b[cycle[i]]; } long long ans0 = solve(cycle, ca, cb); reverse(cycle.begin(), cycle.end()); reverse(ca.begin(), ca.end()); reverse(cb.begin(), cb.end()); long long ans1 = solve(cycle, ca, cb); if (ans0 == -1) { if (ans1 == -1) ans = -1; else ans += ans1; } else { if (ans1 == -1) ans += ans0; else ans += min(ans0, ans1); } if (ans == -1) cout << -1 << '\n'; else cout << leaves[0] + 1 << ' ' << leaves[1] + 1 << ' ' << ans << '\n'; return 0; } ```
#include <bits/stdc++.h> using namespace std; const int N = 200005; using ll = long long; int n, a[N], b[N], c[N], bk[N]; vector<int> v[N]; int fa[N], dep[N]; void dfs1(int pos) { for (auto &i : v[pos]) if (i != fa[pos]) dep[i] = dep[fa[i] = pos] + 1, dfs1(i); } bool check() { for (int i = 1; i <= n; i++) c[i] = b[i]; int p = a[1]; while (fa[p]) swap(c[p], c[fa[p]]), p = fa[p]; for (int i = 1; i <= n; i++) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idx; inline void fail() { cout << -1 << endl; exit(0); } void get(int pos, int id) { if (id > 1 || (id == 1 && fa[st[0][0]] != fa[pos])) fail(); st[id].push_back(pos); while (1) { int vv = 0; for (auto &i : v[pos]) if (c[i] != i && i != fa[pos]) { if (vv) fail(); else vv = i; } if (!vv) break; st[id].push_back(pos = vv); } } int p[N], q[N], len; inline int modlen(int x) { return x >= len ? x - len : x; } void dfs2(int pos) { for (auto &i : v[pos]) if (i != fa[pos]) { if (c[i] != i) get(i, idx++); else dfs2(i); } } int getdis(int x, int y) { int ret = 0; while (x != y) { if (dep[x] < dep[y]) swap(x, y); ++ret; x = fa[x]; } return ret; } int main() { ios::sync_with_stdio(false); cin >> n; int t1, t2; for (int i = 1; i <= n; i++) cin >> a[i], ++a[i], bk[a[i]] = i; for (int i = 1; i <= n; i++) cin >> b[a[i]], ++b[a[i]]; for (int i = 1; i < n; i++) cin >> t1 >> t2, t1 = a[t1], t2 = a[t2], v[t1].push_back(t2), v[t2].push_back(t1); for (int i = 1; i <= n; i++) a[b[i]] = i; dfs1(1); if (check()) { cout << "0 " << dep[a[1]] << endl; return 0; } dfs2(1); for (int i = 1; i <= n; i++) q[i] = -1; for (auto &i : st[0]) p[len] = c[i], q[i] = len++; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (!st[1].empty()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); ll dis = q[p[0]]; for (int i = 1; i < len; i++) if (modlen(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; i++) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); cout << ru << ' ' << rv << ' ' << dis + getdis(a[1], rw) + dep[rw] << endl; return 0; } dis = q[t] >= int(st[0].size()) ? min((dis - 1) * (len + 1) + (q[t] + 1), modlen(len - dis) * ll(len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); cout << ru << ' ' << rv << ' ' << dis + dep[rw] + getdis(a[1], t) << endl; return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 200005; using ll = long long; int n, a[N], b[N], c[N], bk[N]; vector<int> v[N]; int fa[N], dep[N]; void dfs1(int pos) { for (auto &i : v[pos]) if (i != fa[pos]) dep[i] = dep[fa[i] = pos] + 1, dfs1(i); } bool check() { for (int i = 1; i <= n; i++) c[i] = b[i]; int p = a[1]; while (fa[p]) swap(c[p], c[fa[p]]), p = fa[p]; for (int i = 1; i <= n; i++) if (c[i] != i) return 0; return 1; } vector<int> st[2]; int idx; inline void fail() { cout << -1 << endl; exit(0); } void get(int pos, int id) { if (id > 1 || (id == 1 && fa[st[0][0]] != fa[pos])) fail(); st[id].push_back(pos); while (1) { int vv = 0; for (auto &i : v[pos]) if (c[i] != i && i != fa[pos]) { if (vv) fail(); else vv = i; } if (!vv) break; st[id].push_back(pos = vv); } } int p[N], q[N], len; inline int modlen(int x) { return x >= len ? x - len : x; } void dfs2(int pos) { for (auto &i : v[pos]) if (i != fa[pos]) { if (c[i] != i) get(i, idx++); else dfs2(i); } } int getdis(int x, int y) { int ret = 0; while (x != y) { if (dep[x] < dep[y]) swap(x, y); ++ret; x = fa[x]; } return ret; } int main() { ios::sync_with_stdio(false); cin >> n; int t1, t2; for (int i = 1; i <= n; i++) cin >> a[i], ++a[i], bk[a[i]] = i; for (int i = 1; i <= n; i++) cin >> b[a[i]], ++b[a[i]]; for (int i = 1; i < n; i++) cin >> t1 >> t2, t1 = a[t1], t2 = a[t2], v[t1].push_back(t2), v[t2].push_back(t1); for (int i = 1; i <= n; i++) a[b[i]] = i; dfs1(1); if (check()) { cout << "0 " << dep[a[1]] << endl; return 0; } dfs2(1); for (int i = 1; i <= n; i++) q[i] = -1; for (auto &i : st[0]) p[len] = c[i], q[i] = len++; int ru = st[0].back(), rv = fa[st[0].front()], rw = rv; if (!st[1].empty()) { rv = st[1].back(); for (int i = st[1].size() - 1; i >= 0; --i) p[len] = c[st[1][i]], q[st[1][i]] = len, ++len; } if ((ru = bk[ru]) > (rv = bk[rv])) swap(ru, rv); ll dis = q[p[0]]; for (int i = 1; i < len; i++) if (modlen(q[p[i]] - i + len) != dis) fail(); for (int i = 1; i <= n; i++) if (c[i] != i && q[i] == -1) fail(); int t = a[1]; while (q[t] == -1 && t != 1) t = fa[t]; if (t == 1) { dis = min(dis, len - dis) * (len + 1); cout << ru << ' ' << rv << ' ' << dis + getdis(a[1], rw) + dep[rw] << endl; return 0; } dis = q[t] >= int(st[0].size()) ? min((dis - 1) * (len + 1) + (q[t] + 1), modlen(len - dis) * ll(len + 1) + (len - q[t])) : min(dis * (len + 1) + (q[t] + 1), (len - dis - 1) * (len + 1) + (len - q[t])); cout << ru << ' ' << rv << ' ' << dis + dep[rw] + getdis(a[1], t) << endl; return 0; } ```
#include <bits/stdc++.h> using namespace std; int n; int S, T; int a[200050], b[200050]; int anc[200050]; int dep[200050]; int head[200050]; bool in[200050]; bool mark[200050]; vector<int> v; struct edge { int to, nex; edge(int to = 0, int nex = 0) : to(to), nex(nex) {} }; vector<edge> G; void addedge(int u, int v) { G.push_back(edge(v, head[u])), head[u] = G.size() - 1; G.push_back(edge(u, head[v])), head[v] = G.size() - 1; } void dfs(int u) { for (int i = head[u]; ~i; i = G[i].nex) { int v = G[i].to; if (v != anc[u]) { anc[v] = u; dep[v] = dep[u] + 1; dfs(v); } } } bool solve() { dfs(T); for (int u = S;; u = anc[u]) { mark[u] = 1; if (u == T) { break; } else { swap(a[u], a[anc[u]]); } } int s1 = -1, p = -1; int s2 = -1, q = -1; for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (s1 == -1 || dep[s1] < dep[i]) { s1 = i; } } if (s1 == -1) { printf("0 %d\n", dep[S]); return true; } for (p = s1; a[p] != b[p]; p = anc[p]) { v.push_back(p); in[p] = 1; } int m = v.size(); for (int i = 1; i <= n; ++i) if (!in[i] && a[i] != b[i]) { if (s2 == -1 || dep[s2] < dep[i]) { s2 = i; } } if (s2 != -1) { for (q = s2; a[q] != b[q]; q = anc[q]) { if (in[q]) { return false; } v.push_back(q); in[q] = 1; } if (p != q) { return false; } reverse(v.begin() + m, v.end()); } else { s2 = p; } for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (!in[i]) { return false; } } int M = v.size(); int d = -1; for (int i = 1; i < M; ++i) { if (b[v[i]] == a[v[0]]) { d = i; break; } } assert(d != -1); for (int i = 0; i < M; ++i) { if (a[v[i]] != b[v[(i + d) % M]]) { return false; } } printf("%d %d ", min(s1, s2), max(s1, s2)); int cnt = 0; for (int i = 0; i < M; ++i) { if (mark[v[i]]) { ++cnt; } } long long an = dep[S]; if (cnt == 0) { an += (long long)min(d, M - d) * (M + 1); while (!mark[p]) { an += 2; p = anc[p]; } } else { for (int i = m; i < M; ++i) { if (mark[v[i]]) { d = M - d; break; } } an += min((long long)d * (M + 1) - (cnt << 1), (long long)(M - d) * (M + 1)); } printf("%I64d\n", an); return true; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (a[i] == 0) { S = i; } } for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (b[i] == 0) { T = i; } } memset(head, -1, sizeof(head)); for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); addedge(u, v); } if (!solve()) { printf("-1\n"); } return 0; }
### Prompt Create a solution in Cpp for the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; int S, T; int a[200050], b[200050]; int anc[200050]; int dep[200050]; int head[200050]; bool in[200050]; bool mark[200050]; vector<int> v; struct edge { int to, nex; edge(int to = 0, int nex = 0) : to(to), nex(nex) {} }; vector<edge> G; void addedge(int u, int v) { G.push_back(edge(v, head[u])), head[u] = G.size() - 1; G.push_back(edge(u, head[v])), head[v] = G.size() - 1; } void dfs(int u) { for (int i = head[u]; ~i; i = G[i].nex) { int v = G[i].to; if (v != anc[u]) { anc[v] = u; dep[v] = dep[u] + 1; dfs(v); } } } bool solve() { dfs(T); for (int u = S;; u = anc[u]) { mark[u] = 1; if (u == T) { break; } else { swap(a[u], a[anc[u]]); } } int s1 = -1, p = -1; int s2 = -1, q = -1; for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (s1 == -1 || dep[s1] < dep[i]) { s1 = i; } } if (s1 == -1) { printf("0 %d\n", dep[S]); return true; } for (p = s1; a[p] != b[p]; p = anc[p]) { v.push_back(p); in[p] = 1; } int m = v.size(); for (int i = 1; i <= n; ++i) if (!in[i] && a[i] != b[i]) { if (s2 == -1 || dep[s2] < dep[i]) { s2 = i; } } if (s2 != -1) { for (q = s2; a[q] != b[q]; q = anc[q]) { if (in[q]) { return false; } v.push_back(q); in[q] = 1; } if (p != q) { return false; } reverse(v.begin() + m, v.end()); } else { s2 = p; } for (int i = 1; i <= n; ++i) if (a[i] != b[i]) { if (!in[i]) { return false; } } int M = v.size(); int d = -1; for (int i = 1; i < M; ++i) { if (b[v[i]] == a[v[0]]) { d = i; break; } } assert(d != -1); for (int i = 0; i < M; ++i) { if (a[v[i]] != b[v[(i + d) % M]]) { return false; } } printf("%d %d ", min(s1, s2), max(s1, s2)); int cnt = 0; for (int i = 0; i < M; ++i) { if (mark[v[i]]) { ++cnt; } } long long an = dep[S]; if (cnt == 0) { an += (long long)min(d, M - d) * (M + 1); while (!mark[p]) { an += 2; p = anc[p]; } } else { for (int i = m; i < M; ++i) { if (mark[v[i]]) { d = M - d; break; } } an += min((long long)d * (M + 1) - (cnt << 1), (long long)(M - d) * (M + 1)); } printf("%I64d\n", an); return true; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (a[i] == 0) { S = i; } } for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (b[i] == 0) { T = i; } } memset(head, -1, sizeof(head)); for (int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); addedge(u, v); } if (!solve()) { printf("-1\n"); } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 7; int n, s, t, p, x, y, last[maxn], a[maxn], b[maxn], r[maxn], d[maxn]; vector<int> g, h, A, B; pair<int, int> o = {maxn, 0}; struct Edge { int v, nxt; } e[2 * maxn]; int read() { int x = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + (c ^ 48), c = getchar(); return x; } inline void add(int u, int v) { static int cnt = 0; e[++cnt] = {v, last[u]}, last[u] = cnt; } bool dfs1(int u, int fa) { g.push_back(u); if (u == t) return 1; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (dfs1(v, u)) return 1; } g.pop_back(); return 0; } void dfs2(int u, int fa, int d) { if (a[u] != b[u]) { h.push_back(u), r[u] = 1; if (d - 1 == o.first && fa != o.second) printf("-1\n"), exit(0); ; if (d - 1 < o.first) o = {d - 1, fa}; } for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs2(v, u, d + 1); } } void dfs3(int u, int fa) { if (u != p) A.push_back(a[u]), B.push_back(b[u]); for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (r[v]) dfs3(v, u); } } int dfs4(int u, int fa, int d, int t) { if (u == t) return d; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; int ret = dfs4(v, u, d + 1, t); if (ret) return ret; } return 0; } int calc(vector<int> A, vector<int> B) { int pos = 0, siz = A.size(); for (int i = 0; i < B.size(); i++) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (int i = 0; i < A.size(); i++) if (A[i] != B[(i + pos) % siz]) return 0; return pos; } inline int S(int x, int y) { return dfs4(x, 0, 0, y); } inline long long get(int x, int y) { int c = calc(A, B); return S(s, x) + 1ll * (c - 1) * (A.size() + 1) + S(y, t) + 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), s = a[i] ? s : i; for (int i = 1; i <= n; i++) b[i] = read(), t = b[i] ? t : i; for (int i = 1; i < n; i++) { x = read(), y = read(); add(x, y), add(y, x); } dfs1(s, 0); for (int i = 1; i < g.size(); i++) swap(a[g[i - 1]], a[g[i]]); bool flag = 1; for (int i = 1; i <= n; i++) flag &= a[i] == b[i]; if (flag) { printf("0 %d\n", g.size() - 1); return 0; } dfs2(t, 0, 0); h.push_back(p = o.second); r[p] = 1; for (int i = 0; i < h.size(); i++) { int u = h[i]; for (int j = last[u]; j; j = e[j].nxt) { int v = e[j].v; if (r[v]) d[u]++; } } vector<int> c; for (int i = 0; i < h.size(); i++) { int u = h[i]; if (d[u] == 1) c.push_back(u); else if (d[u] != 2) printf("-1\n"), exit(0); ; } if (c.size() != 2) printf("-1\n"), exit(0); ; if (c[0] > c[1]) swap(c[0], c[1]); dfs3(c[0], 0); if (!calc(A, B)) printf("-1\n"), exit(0); ; printf("%d %d ", c[0], c[1]); long long ans = get(c[0], c[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); ans = min(ans, get(c[1], c[0])); printf("%lld\n", ans); return 0; }
### Prompt Please create a solution in cpp to the following problem: A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position. Input The first line contains a single integer n (2 ≀ n ≀ 200 000) β€” the total number of islands. The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1) β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1) β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct. The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input. Output Print a single line of integers: If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement. Otherwise, print u, v, and t (1 ≀ u < v ≀ n) β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement. If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing - 1. Examples Input 3 1 0 2 2 0 1 1 2 2 3 Output 1 3 3 Input 2 1 0 0 1 1 2 Output 0 1 Input 4 0 1 2 3 0 2 3 1 1 2 1 3 1 4 Output -1 Note In the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made. In the third sample, no added bridge and subsequent movements result in the desired position. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 7; int n, s, t, p, x, y, last[maxn], a[maxn], b[maxn], r[maxn], d[maxn]; vector<int> g, h, A, B; pair<int, int> o = {maxn, 0}; struct Edge { int v, nxt; } e[2 * maxn]; int read() { int x = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + (c ^ 48), c = getchar(); return x; } inline void add(int u, int v) { static int cnt = 0; e[++cnt] = {v, last[u]}, last[u] = cnt; } bool dfs1(int u, int fa) { g.push_back(u); if (u == t) return 1; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (dfs1(v, u)) return 1; } g.pop_back(); return 0; } void dfs2(int u, int fa, int d) { if (a[u] != b[u]) { h.push_back(u), r[u] = 1; if (d - 1 == o.first && fa != o.second) printf("-1\n"), exit(0); ; if (d - 1 < o.first) o = {d - 1, fa}; } for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; dfs2(v, u, d + 1); } } void dfs3(int u, int fa) { if (u != p) A.push_back(a[u]), B.push_back(b[u]); for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; if (r[v]) dfs3(v, u); } } int dfs4(int u, int fa, int d, int t) { if (u == t) return d; for (int i = last[u]; i; i = e[i].nxt) { int v = e[i].v; if (v == fa) continue; int ret = dfs4(v, u, d + 1, t); if (ret) return ret; } return 0; } int calc(vector<int> A, vector<int> B) { int pos = 0, siz = A.size(); for (int i = 0; i < B.size(); i++) if (B[i] == A[0]) pos = i; if (!pos) return 0; for (int i = 0; i < A.size(); i++) if (A[i] != B[(i + pos) % siz]) return 0; return pos; } inline int S(int x, int y) { return dfs4(x, 0, 0, y); } inline long long get(int x, int y) { int c = calc(A, B); return S(s, x) + 1ll * (c - 1) * (A.size() + 1) + S(y, t) + 1; } int main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), s = a[i] ? s : i; for (int i = 1; i <= n; i++) b[i] = read(), t = b[i] ? t : i; for (int i = 1; i < n; i++) { x = read(), y = read(); add(x, y), add(y, x); } dfs1(s, 0); for (int i = 1; i < g.size(); i++) swap(a[g[i - 1]], a[g[i]]); bool flag = 1; for (int i = 1; i <= n; i++) flag &= a[i] == b[i]; if (flag) { printf("0 %d\n", g.size() - 1); return 0; } dfs2(t, 0, 0); h.push_back(p = o.second); r[p] = 1; for (int i = 0; i < h.size(); i++) { int u = h[i]; for (int j = last[u]; j; j = e[j].nxt) { int v = e[j].v; if (r[v]) d[u]++; } } vector<int> c; for (int i = 0; i < h.size(); i++) { int u = h[i]; if (d[u] == 1) c.push_back(u); else if (d[u] != 2) printf("-1\n"), exit(0); ; } if (c.size() != 2) printf("-1\n"), exit(0); ; if (c[0] > c[1]) swap(c[0], c[1]); dfs3(c[0], 0); if (!calc(A, B)) printf("-1\n"), exit(0); ; printf("%d %d ", c[0], c[1]); long long ans = get(c[0], c[1]); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); ans = min(ans, get(c[1], c[0])); printf("%lld\n", ans); return 0; } ```