这道题我 TLE 0pt,但是我把数组 seg 存边的,换成 50005 会RE,可是scp020 开 10000 却会 AC,不知道为什么,我还交了一下,是可以AC的。
#include <stdio.h>
int T, n, a[500005], h[500005],x, y, z,seg[50005][2],sz[500005], dep[500005], son[500005],vson[500005],top[500005], fa[500005],dfn[500005],cnt;
struct node
{
int to,w,nxt;
}v[500005];
struct nde
{
int mx,l,r;
}t[500005];
char c[10];
int max(int x,int y)
{
if(x>y)return x;
return y;
}
void swap(int *x,int *y)
{
int t=*x;
*x=*y,*y=t;
}
inline int read() {
char c = getchar();
int sum = 0;
while ((c < '0' || c > '9')) c = getchar();
do {
sum = (sum << 3) + (sum << 1) + c - '0';
c = getchar();
} while (c >= '0' && c <= '9');
return sum;
}
void dfs1(int x) {
sz[x] = 1, dep[x] = dep[fa[x]] + 1;
for (int p=h[x];p;p=v[p].nxt) {
if (v[p].to == fa[x])
continue;
fa[v[p].to] = x;
dfs1(v[p].to);
sz[x] += sz[v[p].to];
if (sz[son[x]] < sz[v[p].to])
son[x] = v[p].to,vson[x]=v[p].w;
}
}
void dfs2(int x, int t,int w) {
top[x] = t,dfn[x]=++cnt,a[cnt]=w;
if (son[x])
dfs2(son[x], t,vson[x]);
for (int p=h[x];p;p=v[p].nxt) {
if (v[p].to == fa[x] || v[p].to == son[x])
continue;
dfs2(v[p].to, v[p].to,v[p].w);
}
}
void build(int pos,int l,int r)
{
t[pos].l=l;
t[pos].r=r;
if(l==r)
{
t[pos].mx=a[l];
return;
}
int mid=(l+r)>>1;
build(pos<<1,l,mid);
build((pos<<1)|1,mid+1,r);
t[pos].mx=max(t[pos<<1].mx,t[(pos<<1)|1].mx);
}
void change(int pos,int l,int k)
{
if(l<t[pos].l||t[pos].r<l)return;
if(t[pos].l==t[pos].r)
{
t[pos].mx=k;
return;
}
if(l<=t[pos<<1].r)change(pos<<1,l,k);
else change((pos<<1)|1,l,k);
t[pos].mx=max(t[pos<<1].mx,t[(pos<<1)|1].mx);
}
int querymx(int pos,int l,int r)
{
if(r<t[pos].l||t[pos].r<l)return 0;
if(l<=t[pos].l&&t[pos].r<=r)return t[pos].mx;
return max(querymx(pos<<1,l,r),querymx((pos<<1)|1,l,r));
}
int query(int x,int y)
{
int tx=top[x],ty=top[y],ans=0;
while (tx!=ty) {
if(dep[tx]<dep[ty])
{
swap(&tx,&ty);
}
ans=max(querymx(1,dfn[tx],dfn[x]),ans);
x=fa[tx],tx=top[x];
}
if (dep[x] > dep[y])
{
swap(&x,&y);
}
ans=max(ans,querymx(1,dfn[son[x]],dfn[y]));
return ans;
}
int tot;
void add(int x,int y,int z)
{
v[++tot].to=y;
v[tot].w=z;
v[tot].nxt=h[x];
h[x]=tot;
}
int main() {
T=read();
while(T--)
{
cnt=0,tot=0;
n=read();
for (int i = 1; i <= n - 1; i++) {
x=read(),y=read(),z=read();
seg[i][0]=x,seg[i][1]=y;
add(x,y,z),add(y,x,z);
}
dfs1(1);
dfs2(1,1,0);
build(1,1,n);
while(1)
{
scanf("%s",c);
if(c[0]=='D')break;
x=read(),y=read();
if(c[0]=='Q')
{
printf("%d\n",query(x,y));
}
else
{
if(dep[seg[x][0]]>dep[seg[x][1]])swap(&seg[x][0],&seg[x][1]);
change(1,dfn[seg[x][1]],y);
}
}
for(int i=1;i<=n;i++)
{
h[i]=0,son[i]=0;
}
}
}