题解
对于这种无序点对统计问题,我们可以遍历每一个点,然后计算其与之前遍历过的点的配对
\(dfs\) 遍历,设 \(num[i]\) 代表遍历到当前节点时,有多少可与当前节点配对的、节点颜色为 \(i\) 的、且 \(dfs\) 序小于当前节点(即之前遍历过的)的节点
维护方法:每往子节点遍历,由于子树内,颜色与当前节点相同的节点,能接触到的 \(dfs\) 序最小的节点就是当前节点,所以要令 \(num[color[now]]=1\)
所有子节点遍历完成后,设当前节点颜色为 \(c\),由于接下来遍历的节点可以接触的 \(c\) 加一,所以 \(num[c]++\)
代码有些细节自行领会
code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
vector<ll> G[200005];
ll num[200005]={0};
ll color[200005];
ll ans=0;
void dfs(ll now,ll fa)
{
ll c=color[now];
ll tem=num[c];
ans+=tem;
for(auto next:G[now])
if(next!=fa)
{
num[c]=1;
dfs(next,now);
}
num[c]=tem+1;
}
void solve()
{
ll n;
cin>>n;
for(ll i=1;i<=n;i++) cin>>color[i];
for(ll i=1;i<n;i++)
{
ll x,y;
cin>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
dfs(1,1);
cout<<ans<<'\n';
ans=0;
for(ll i=1;i<=n;i++)
{
G[i].clear();
num[i]=0;
}
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll t=1;
cin>>t;
while(t--) solve();
return 0;
}
标签:Count,Paths,遍历,ll,dfs,num,now,节点
From: https://www.cnblogs.com/pure4knowledge/p/18299410