标签:
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1162 Accepted Submission(s): 339
#include <cstdio> #include <vector> #include <cstring> using namespace std; const int MAXN=100001; typedef long long LL; vector<LL> divisor[MAXN]; void prep() { for(LL e=1;e<MAXN;e++) { LL x=e; for(LL i=2;i*i<=x;i++) { if(x%i==0) { divisor[e].push_back(i); while(x%i==0) x/=i; } } if(x>1) divisor[e].push_back(x); } } vector<int> arc[MAXN]; int n,val[MAXN]; int cnt[MAXN],res[MAXN]; int cal(int n,int type)//求集合S中与n不互素的数的个数 { int ans=0; for(LL mark=1;mark<(1<<divisor[n].size());mark++) { LL odd=0; LL mul=1; for(LL i=0;i<divisor[n].size();i++) { if(mark&(1<<i)) { odd++; mul*=divisor[n][i]; } } if(odd&1) ans+=cnt[mul]; else ans-=cnt[mul]; cnt[mul]+=type; } return ans; } int dfs(int u,int fa) { int pre=cal(val[u],0); int s=0; for(int i=0;i<arc[u].size();i++) { int to=arc[u][i]; if(to!=fa) { s+=dfs(to,u); } } int post=cal(val[u],1); res[u]=s-(post-pre);//以u为根的子树结点数目-(遍历u之前与u不互素的结点数目-遍历u之后与u不互素的结点数目) if(val[u]==1) res[u]++;//若u的值为1,那么u与自身互素 return s+1; } int main() { prep(); int cas=0; while(scanf("%d",&n)!=EOF) { memset(cnt,0,sizeof(cnt)); for(int i=1;i<=n;i++) arc[i].clear(); for(int i=0;i<n-1;i++) { int u,v; scanf("%d%d",&u,&v); arc[u].push_back(v); arc[v].push_back(u); } for(int i=1;i<=n;i++) { scanf("%d",&val[i]); } dfs(1,-1); printf("Case #%d: ",++cas); for(int i=1;i<n;i++) { printf("%d ",res[i]); } printf("%d\n",res[n-1]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5813771.html