hdu5029 Relief grain

时间:2022-08-07 21:07:59

题目链接

树剖+线段树

将区间修改转化为单点修改,因为如果按DFS序进行修改,那么一定会对DFS序更大的点造成影响

 #include<iostream>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#define re(i,l,r) for(int i=(l);i<=(r);i++)
using namespace std;
template <typename Q>
void inin(Q &ret)
{
ret=;int f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='')f=;ch=getchar();}
while(ch>=''&&ch<='')ret=(ret<<)+(ret<<)+ch-'',ch=getchar();
ret=f?-ret:ret;
}
const int xxx=;
int head[xxx],Next[xxx<<],zhi[xxx<<],n,m,dui[xxx],ans[xxx];
int top[xxx],shen[xxx],fa[xxx],ed,dfn[xxx],son[xxx];
vector<int>in[xxx],out[xxx];
void add(int a,int b)
{
Next[++ed]=head[a],head[a]=ed,zhi[ed]=b;
Next[++ed]=head[b],head[b]=ed,zhi[ed]=a;
}
int dfs(int x)
{
int ret=,Max=,temp;
for(int i=head[x];i;i=Next[i])if(zhi[i]!=fa[x])
{
fa[zhi[i]]=x,shen[zhi[i]]=shen[x]+;
temp=dfs(zhi[i]);
ret+=temp;
if(Max<temp)Max=temp,son[x]=zhi[i];
}
return ret;
}
int tot;
void dfs(int x,int t)
{
if(!x)return ;
top[x]=t;dfn[x]=++tot,dui[tot]=x;
dfs(son[x],t);
for(int i=head[x];i;i=Next[i])if(zhi[i]!=fa[x]&&zhi[i]!=son[x])
dfs(zhi[i],zhi[i]);
}
void change(int x,int y,int z)
{
while(top[x]!=top[y])
if(shen[top[x]]>shen[top[y]])
in[dfn[top[x]]].push_back(z),
out[dfn[x]+].push_back(z),
x=fa[top[x]];
else in[dfn[top[y]]].push_back(z),
out[dfn[y]+].push_back(z),
y=fa[top[y]];
if(shen[x]>shen[y])swap(x,y);
in[dfn[x]].push_back(z),out[dfn[y]+].push_back(z);
}
struct tree
{
int l,r,Max,o;
}t[];
void UP(int k)
{
int p1=k<<,p2=p1|;
if(t[p1].Max>=t[p2].Max)t[k].Max=t[p1].Max,t[k].o=t[p1].o;
else t[k].Max=t[p2].Max,t[k].o=t[p2].o;
}
void build(int k,int l,int r)
{
t[k].l=l,t[k].r=r;t[k].Max=,t[k].o=l;
if(l==r)return ;
int mid=(l+r)>>,p1=k<<,p2=p1|;
build(p1,l,mid),build(p2,mid+,r);
UP(k);
}
void update(int k,int se,int x)
{
if(t[k].l==t[k].r){t[k].Max+=x;return ;}
int mid=(t[k].l+t[k].r)>>,p1=k<<,p2=p1|;
if(se<=mid)update(p1,se,x);
else update(p2,se,x);
UP(k);
}
int main()
{
while(scanf("%d%d",&n,&m),n)
{
tot=;
ed=;memset(head,,sizeof head);
memset(son,,sizeof son);
re(i,,n)
{
int a,b;inin(a),inin(b);
add(a,b);
}
dfs();
dfs(,);int Max=;
// re(i,1,n)
// {
// printf("%d : ",i);
// cout<<"in:";re(j,0,(int)in[i].size()-1)printf("%d ",in[i][j]);cout<<"\n";
// cout<<"out:";re(j,0,(int)out[i].size()-1)printf("%d ",out[i][j]);cout<<"\n";
// }
re(i,,m)
{
int x,y,z;
inin(x),inin(y),inin(z);
change(x,y,z),Max=max(Max,z);
}
build(,,Max+);
re(i,,n)
{
re(j,,(int)in[i].size()-)
update(,in[i][j],);
re(j,,(int)out[i].size()-)
update(,out[i][j],-);
ans[dui[i]]=t[].Max?t[].o:;
}
re(i,,n)printf("%d\n",ans[i]);
re(i,,n+)in[i].clear(),out[i].clear();
}
return ;
}