luogu P1315 联合权值 枚举
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 typedef long long ll; 5 const int N = 200100,M = 400100,mo = 10007;//用变量方便更改 6 int cnt,n,maxn; 7 ll ans; 8 int w[N],head[N],to[M],nxt[M]; 9 void add(int x,int y) 10 { 11 nxt[++cnt] = head[x]; 12 to[cnt] = y; 13 head[x] = cnt; 14 } 15 void dfs(int x,int fa) 16 { 17 ll sum = 0; 18 int max1 = 0,max2 = 0; 19 for (int i = head[x];i;i = nxt[i]) 20 { 21 sum += w[to[i]]; 22 if (w[to[i]] > max1)//赋值顺序一定要考虑清楚 23 { 24 max2 = max1; 25 max1 = w[to[i]]; 26 }else if (w[to[i]] > max2)//一定要写else,否则? 27 max2 = w[to[i]]; 28 } 29 maxn = max(maxn,max1 * max2); 30 for (int i = head[x];i;i = nxt[i]) 31 { 32 ans += (sum - w[to[i]]) * w[to[i]]; 33 ans %= mo; 34 } 35 for (int i = head[x];i;i = nxt[i]) 36 if (to[i] != fa) 37 dfs(to[i],x); 38 } 39 int main() 40 { 41 scanf("%d",&n); 42 int u,v; 43 for (int i = 1;i <= n - 1;i++) 44 { 45 scanf("%d%d",&u,&v); 46 add(u,v); 47 add(v,u); 48 } 49 for (int i = 1;i <= n;i++) 50 scanf("%d",&w[i]); 51 dfs(1,0); 52 printf("%d %lld\n",maxn,ans); 53 return 0; 54 }
心之所动 且就随缘去吧