#include<cstdio> #include<cstring> using namespace std; const int MAX_N=100005; struct Edge{ int v,id,next; }edge[MAX_N*4]; int a[MAX_N],b[MAX_N],to[MAX_N],k[MAX_N],lca[MAX_N]; int head[MAX_N],opr[MAX_N],fa[MAX_N],father[MAX_N]; int cnt; long long valnode[MAX_N],valedge[MAX_N]; bool type[MAX_N],vis[MAX_N]; void init() { memset(valnode,0,sizeof(valnode)); memset(valedge,0,sizeof(valedge)); memset(opr,-1,sizeof(opr)); memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); cnt=0; } int findfa(int a) { return father[a]==a?a:findfa(father[a]); } void addedge(int u,int v, int id) { edge[cnt].v=v; edge[cnt].next=head[u]; edge[cnt].id=id; head[u]=cnt++; } void addopr(int u,int v, int id) { edge[cnt].v=v; edge[cnt].next=opr[u]; edge[cnt].id=id; opr[u]=cnt++; } void LCA(int now, int f) { father[now]=now; fa[now]=f; vis[now]=true; for(int i=opr[now];i!=-1;i=edge[i].next) { int v=edge[i].v; int id=edge[i].id; if(vis[v]) lca[id]=findfa(v); } for(int i=head[now];i!=-1;i=edge[i].next) { int v=edge[i].v; int id=edge[i].id; if(v==f) continue; LCA(v,now); to[id]=v; father[v]=now; } } void getans(int now, int fa) { for(int i=head[now];i!=-1;i=edge[i].next) { int v=edge[i].v; int id=edge[i].id; if(v==fa) continue; getans(v,now); valnode[now]+=valnode[v]; valedge[now]+=valedge[v]; } } int main() { int n,m,t; scanf("%d",&t); int l=0; while(l<t) { init(); scanf("%d %d",&n,&m); for(int i=0;i<n-1;i++) { int u,v; scanf("%d %d",&u,&v); addedge(u,v,i); addedge(v,u,i); } for(int i=0;i<m;i++) { char str[5]; scanf("%s",str); scanf("%d %d %d",&a[i],&b[i],&k[i]); type[i]=str[3]==‘1‘; addopr(a[i],b[i],i); addopr(b[i],a[i],i); } LCA(1,-1); fa[1]=0; for(int i=0;i<m;i++) { if(type[i]) { valnode[a[i]]+=k[i]; valnode[b[i]]+=k[i]; valnode[lca[i]]-=k[i]; valnode[fa[lca[i]]]-=k[i]; } else { valedge[a[i]]+=k[i]; valedge[b[i]]+=k[i]; valedge[lca[i]]-=k[i]*2; } } getans(1,-1); printf("Case #%d:\n",++l); for(int i=1;i<=n;i++) { if(i!=1) putchar(‘ ‘); printf("%I64d",valnode[i]); } putchar(‘\n‘); for(int i=0;i<n-1;i++) { if(i) putchar(‘ ‘); printf("%I64d",valedge[to[i]]); } puts(""); } return 0; }
时间: 2024-10-27 10:39:56