【题目链接】
【思路要点】
- 分别考虑1和\(N\)之间是否有边直接相连。
- 若有边相连,所有到1和\(N\)距离的差值的绝对值应该相等。
- 否则,到1和\(N\)距离的和的最小值就是1到\(N\)的距离,将这条链构造出来,将其它点逐一挂在上面即可。
- 时间复杂度\(O(N+D)\)。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 5e5 + 5; const int MAXV = 2e6 + 5; 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; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } int a[MAXN], b[MAXN], p[MAXV]; int c[MAXN], x[MAXN], y[MAXN]; bool check(int n) { int val = abs(a[2] - b[2]); if (val == 0) return false; for (int i = 3; i <= n - 1; i++) if (abs(a[i] - b[i]) != val) return false; printf("TAK\n%d %d %d\n", 1, n, val); for (int i = 2; i <= n - 1; i++) if (a[i] <= b[i]) printf("%d %d %d\n", i, 1, a[i]); else printf("%d %d %d\n", i, n, b[i]); return true; } int main() { int n; read(n); if (n == 2) { printf("TAK\n%d %d %d\n", 1, n, 1); return 0; } for (int i = 2; i <= n - 1; i++) read(a[i]); for (int i = 2; i <= n - 1; i++) read(b[i]); if (check(n)) return 0; int Min = 1e7; for (int i = 2; i <= n - 1; i++) chkmin(Min, a[i] + b[i]); p[0] = 1, p[Min] = n; for (int i = 2; i <= n - 1; i++) if (Min == a[i] + b[i]) { if (p[a[i]] != 0) { printf("NIE\n"); return 0; } p[a[i]] = i; } int m = 0; int last = 0; for (int i = 1; i <= Min; i++) if (p[i]) { c[++m] = i - last; x[m] = p[last], y[m] = p[i]; last = i; } for (int i = 2; i <= n - 1; i++) if (Min != a[i] + b[i]) { int tmp = a[i] + b[i] - Min; if (tmp & 1) { printf("NIE\n"); return 0; } int tnp = a[i] - tmp / 2; if (tnp < 0 || p[tnp] == 0) { printf("NIE\n"); return 0; } c[++m] = tmp / 2; x[m] = p[tnp]; y[m] = i; } printf("TAK\n"); for (int i = 1; i <= m; i++) printf("%d %d %d\n", x[i], y[i], c[i]); return 0; }