shadow__ @ 2018-01-21 19:42:48
spoj上过了,数组大小也改了,但是只有前4组后6组全都RE。
#include<bits/stdc++.h>
#define OL(o) o<<1
#define OR(o) o<<1|1
const int MAXN = 1e6;
const int INF = 2147483000;
using namespace std;
inline int Read() {
int x=0,f=1;
char ch=getchar();
while(!isdigit(ch)) {
if(ch == '-')f=-1;
ch=getchar();
}
while(isdigit(ch)) {
x=x*10+ch-'0';
ch=getchar();
}
return f*x;
}
struct node {
int v,w,next;
} E[MAXN*2+10];
int head[MAXN+10],e;
inline void insert(int u,int v,int w) {
E[++e].v=v;
E[e].w=w;
E[e].next=head[u];
head[u]=e;
}
int T,N;
int K[MAXN+10],fa[MAXN+10],Son[MAXN+10];
int Top[MAXN+10],Dfn[MAXN+10],Deep[MAXN+10],dfs_clock;
int A[MAXN+10];
int tree[MAXN*10+10];
pair<int,int>road[MAXN+10];
inline void buildtree(int o,int l,int r) {
if(l == r) {
tree[o]=A[l];
return ;
}
int mid = (l+r)>>1;
buildtree(OL(o),l,mid);
buildtree(OR(o),mid+1,r);
tree[o]=max(tree[OL(o)],tree[OR(o)]);
}
int treequery(int o,int l,int r,int ql,int qr) {
if(l>=ql&&r<=qr)return tree[o];
int mid = (l+r)>>1;
int p1=-INF,p2=-INF;
if(ql<=mid)p1=treequery(OL(o),l,mid,ql,qr);
if(qr>mid)p2=treequery(OR(o),mid+1,r,ql,qr);
return max(p1,p2);
}
inline void updata(int o,int l,int r,int p,int v) {
if(l == r) {
tree[o]=v;
return ;
}
int mid = (l+r)>>1;
if(p<=mid)updata(OL(o),l,mid,p,v);
else updata(OR(o),mid+1,r,p,v);
tree[o]=max(tree[OL(o)],tree[OR(o)]);
}
inline void dfs1(int u) {
int maxn = -INF;
for(int i=head[u]; i; i=E[i].next) {
int v=E[i].v,w=E[i].w;
if(v == fa[u])continue;
fa[v]=u;
Deep[v]=Deep[u]+1;
dfs1(v);
K[u]+=K[v];
if(K[v]>maxn) {
Son[u]=v;
maxn=K[v];
}
}
}
inline void dfs2(int u,int anc) {
Dfn[u]=++dfs_clock;
Top[u]=anc;
if(Son[u])dfs2(Son[u],anc);
for(int i=head[u]; i; i=E[i].next) {
int v=E[i].v,w=E[i].w;
if(v == Son[u]) {
A[Dfn[v]]=w;
continue;
}
if(v == fa[u])continue;
dfs2(v,v);
A[Dfn[v]]=w;
}
}
inline void dfs3(int u) {
for(int i=head[u]; i; i=E[i].next) {
int v=E[i].v,w=E[i].w;
if(v == fa[u])continue;
A[Dfn[v]]=w;
dfs3(v);
}
}
inline void prepare() {
dfs1(1),dfs2(1,1);
buildtree(1,1,N);
}
int HLDquery(int u,int v) {
int ret = 0;
while(Top[u] != Top[v]) {
if(Deep[Top[u]]<Deep[Top[v]])swap(u,v);
ret = max(ret,treequery(1,1,N,Dfn[Top[u]],Dfn[u]));
u=fa[Top[u]];
}
if(Dfn[u]<Dfn[v])swap(u,v);
ret = max(ret,treequery(1,1,N,Dfn[v]+1,Dfn[u]));
return ret;
}
int main() {
char q[10];
N=Read();
int u,v,w,p;
for(int i=1; i<N; i++) {
u=Read(),v=Read(),w=Read();
insert(u,v,w);
insert(v,u,w);
road[i]=make_pair(u,v);
}
prepare();
scanf("%s",q);
while(q[0] != 'D') {
if(q[0] == 'C') {
p=Read(),w=Read();
u=road[p].first,v=road[p].second;
if(Dfn[u]<Dfn[v])swap(u,v);
updata(1,1,N,Dfn[u],w);
}
if(q[0] == 'Q') {
u=Read(),v=Read();
printf("%d\n",HLDquery(u,v));
}
scanf("%s",q);
}
return 0;
}
by Night_Aurora @ 2018-01-21 21:25:07
@shadow__
你这代码spoj上能过表示不信...
1.HLDquery的倒数第二行没考虑到u=v的情况
2.dfs1里没有对子树大小K[u]赋初值,然后就变成随意剖分了
by shadow__ @ 2018-01-21 21:27:29
@Night_Aurora emmmmm好像是的,不过貌似spoj上面是过了的。。谢谢啦。。