1. 程式人生 > >洛谷 1351 聯合權值

洛谷 1351 聯合權值

【題解】

  每個點維護各個兒子的前後綴最大值、權值和,這樣就可以統計兒子之間相乘的答案。然後每個節點再乘它的祖父的權值去更新答案即可。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define LL long long
 5 #define rg register
 6 #define N 200010
 7 #define Mod (10007)
 8 using namespace std;
 9 int n,tot,last[N],fa[N],w[N],son[N];
10 LL Sum,Mx; 11 struct edge{int to,pre;}e[N<<1]; 12 inline int read(){ 13 int k=0,f=1; char c=getchar(); 14 while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar(); 15 while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar(); 16 return k*f; 17 } 18 void dfs(int x){ 19 Mx=max(Mx,1ll*w[x]*w[fa[fa[x]]]);
20 Sum+=2*w[x]*w[fa[fa[x]]]; Sum%=Mod; 21 LL s=0,premx=-2e9; int top=0; 22 for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa[x]){ 23 fa[to]=x; s+=w[to]; son[++top]=to; 24 Mx=max(Mx,premx*w[to]); premx=max(premx,1ll*w[to]); 25 } 26 premx=-2e9; 27 for(rg int
i=top,to;i;i--){ 28 Mx=max(Mx,premx*w[to=son[i]]); premx=max(premx,1ll*w[to]); 29 Sum+=w[to]*(s-w[to]); Sum%=Mod; 30 } 31 for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa[x]) dfs(to); 32 } 33 int main(){ 34 n=read(); 35 for(rg int i=1;i<n;i++){ 36 int u=read(),v=read(); 37 e[++tot]=(edge){u,last[v]}; last[v]=tot; 38 e[++tot]=(edge){v,last[u]}; last[u]=tot; 39 } 40 for(rg int i=1;i<=n;i++) w[i]=read(); 41 dfs(1); 42 printf("%lld %lld\n",Mx,Sum%Mod); 43 }