Description
给定一大小为n的有点权树,每次询问一对点(u,v),问是否能在u到v的简单路径上取三个点权,以这三个权值为边长构成一个三角形。同时还支持单点修改。
Sample Input
5 5
1 2 3 4 5
1 2
2 3
3 4
1 5
0 1 3
0 4 5
1 1 4
0 2 5
0 2 3
Sample Output
N
Y
Y
N
你将数列排序后,肯定是相邻几项组成三角形。
你发现最坏情况只能是一个Fibonacci数列,你发现差不多到50项就爆LL了,于是如果两点之间差了50个点及以上就直接YES,否则就利用第一个性质暴力判。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
int s = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * f;
}
struct edge {
int x, y, next;
} e[210000]; int len, last[110000];
int a[110000], dep[110000], fa[20][110000];
LL tp, sta[51];
void ins(int x, int y) {
e[++len].x = x, e[len].y = y;
e[len].next = last[x], last[x] = len;
}
void dfs(int x) {
for(int i = 1; (1 << i) <= dep[x]; i++) fa[i][x] = fa[i - 1][fa[i - 1][x]];
for(int k = last[x]; k; k = e[k].next) {
int y = e[k].y;
if(y != fa[0][x]) fa[0][y] = x, dep[y] = dep[x] + 1, dfs(y);
}
}
int LCA(int x, int y) {
if(dep[x] > dep[y]) swap(x, y);
for(int i = 18; i >= 0; i--) if(dep[y] - dep[x] >= (1 << i)){
y = fa[i][y];
} if(x == y) return x;
for(int i = 18; i >= 0; i--) if(fa[i][x] != fa[i][y]){
x = fa[i][x], y = fa[i][y];
} return fa[0][x];
}
int main() {
int n = read(), q = read();
for(int i = 1; i <= n; i++) a[i] = read();
for(int i = 1; i < n; i++) {
int x = read(), y = read();
ins(x, y), ins(y, x);
} dfs(1);
for(int i = 1; i <= q; i++) {
int opt = read(), x = read(), y = read();
if(opt == 1) a[x] = y;
else {
int lca = LCA(x, y);
int s = dep[x] + dep[y] - dep[lca] - dep[fa[0][lca]];
if(s >= 50) puts("Y");
else {
tp = 0;
while(x != lca) sta[++tp] = a[x], x = fa[0][x];
while(y != lca) sta[++tp] = a[y], y = fa[0][y];
sta[++tp] = a[lca];
sort(sta + 1, sta + tp + 1);
bool bk = 0;
for(int i = 3; i <= tp; i++) {
if(sta[i] < sta[i - 1] + sta[i - 2]) {bk = 1; break;}
} if(bk) puts("Y");
else puts("N");
}
}
}
return 0;
}