HackerEarth The Grass Type
std::map的啓發式合併,樹上問題
題意
一棵樹,每個節點有一個int。問每個節點u的子樹中,兩個不同節點(a,b)滿足val[a]*val[b]=val[u]的pair(a,b)有多少個。
思路
map的啓發式合併,dfs時將子樹的結果合併到根上,並查詢pair即可。複雜度
代碼
#include<bits/stdc++.h>
#define M(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long LL;
const int MAXN=100007;
struct Edge
{
int to, ne;
}e[MAXN<<1];
int head[MAXN], edgenum, v[MAXN];
inline void addedge(int u, int v)
{
e[edgenum].to=v, e[edgenum].ne=head[u], head[u]=edgenum++;
}
map<int, int> mp[MAXN];
LL ans;
void dfs(int u, int fa)
{
mp[u][v[u]]=1;
for(int i=head[u];~i;i=e[i].ne)
{
int to=e[i].to;
if(to==fa) continue;
dfs(to, u);
if(mp[to].size()>mp[u].size())
swap(mp[to], mp[u]);
for(auto tmp : mp[to])
if(v[u]%tmp.first==0)
ans+=((LL)mp[u][v[u]/tmp.first]*tmp.second);
for(auto tmp:mp[to])
mp[u][tmp.first]+=tmp.second;
}
}
int main()
{
int n;
while(scanf("%d", &n)==1)
{
M(head, -1), edgenum=ans=0;
for(int i=1;i<n;i++)
{
int t1, t2;scanf("%d%d", &t1, &t2);
addedge(t1, t2);
addedge(t2, t1);
mp[i].clear();
}
mp[n].clear();
for(int i=1;i<=n;i++) scanf("%d", &v[i]);
dfs(1, -1);
printf("%lld\n", ans);
}
return 0;
}