题目链接:点击查看
题意:
- Change the colours of all vertices in the subtree of the vertex v to the colour c.
- Find the number of different colours in the subtree of the vertex v.
题解:dfs序 搞一下, 剩下的就写吧,刚学了bitset,挺好用的,复杂度还低
#include<bits/stdc++.h>
using namespace std;
const int N=4e5+10;
struct node{
int l,r;
int laz;
bitset<60> s;
}tree[N<<2];
int n,m;
int p[N],in[N],out[N],cnt;
vector<int> v[N];
int val[N];
void dfs(int u,int fa)
{
in[u]=++cnt;
p[cnt]=u;
int l=v[u].size(),to;
for(int i=0;i<l;i++)
{
to=v[u][i];
if(to==fa) continue;
dfs(to,u);
}
out[u]=cnt;
}
void pushup(int cur)
{
tree[cur].s=tree[cur<<1].s|tree[cur<<1|1].s;
}
void build(int l,int r,int cur)
{
int mid;
tree[cur].l=l;
tree[cur].r=r;
if(l==r)
{
tree[cur].s[val[p[l]]-1]=1;
return;
}
mid=(r+l)>>1;
build(l,mid,cur<<1);
build(mid+1,r,cur<<1|1);
pushup(cur);
// cout<<l<<" "<<r<<" "<<tree[cur].s.count()<<endl;
}
void pushdown(int cur)
{
if(tree[cur].laz)
{
tree[cur<<1].laz=tree[cur].laz;
tree[cur<<1|1].laz=tree[cur].laz;
tree[cur<<1].s=0;
tree[cur<<1].s[tree[cur].laz-1]=1;
tree[cur<<1|1].s=0;
tree[cur<<1|1].s[tree[cur].laz-1]=1;
tree[cur].laz=0;
}
}
void update(int pl,int pr,int cur,int val)
{
// cout<<tree[cur].l<<" "<<tree[cur].r<<endl;
if(pl<=tree[cur].l&&tree[cur].r<=pr)
{
tree[cur].s=0;tree[cur].s[val-1]=1;
tree[cur].laz=val;
return;
}
pushdown(cur);
if(pl<=tree[cur<<1].r) update(pl,pr,cur<<1,val);
if(pr>=tree[cur<<1|1].l) update(pl,pr,cur<<1|1,val);
pushup(cur);
}
bitset<60> ans;
void query(int pl,int pr,int cur)
{
if(pl<=tree[cur].l&&tree[cur].r<=pr)
{
ans|=tree[cur].s;
return;
}
pushdown(cur);
if(pl<=tree[cur<<1].r) query(pl,pr,cur<<1);
if(pr>=tree[cur<<1|1].l) query(pl,pr,cur<<1|1);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&val[i]);
int x,y;
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
v[x].push_back(y);
v[y].push_back(x);
}
dfs(1,0);
build(1,n,1);
int op;
while(m--)
{
scanf("%d",&op);
if(op==1)
{
scanf("%d%d",&x,&y);
// cout <<in[x]<<" "<<out[x]<<endl;
update(in[x],out[x],1,y);
}
else
{
ans=0;
scanf("%d",&x);
// cout<<in[x]<<" "<<out[x]<<endl;
query(in[x],out[x],1);
printf("%d\n",ans.count());
}
}
return 0;
}