B. 齐心抗疫

B. 齐心抗疫

 

 

 题解:

 AC_Code:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <string>
 6 using namespace std;
 7 typedef long long ll;
 8 const int maxn = 5e4+10;
 9 const int inf = 0x3f3f3f3f;
10 const int mod = 998244353;
11 #define rep(i,first,second) for(int i=first;i<=second;i++)
12 #define dep(i,first,second) for(int i=first;i>=second;i--)
13 
14 struct edge{int to,nxt;}e[maxn<<1];
15 int head[maxn<<1],tot;
16 int n,a[maxn];
17 int maxdis,maxv;
18 int d1[maxn],d2[maxn];
19 
20 void add(int u,int v){
21     e[tot].to = v;
22     e[tot].nxt = head[u];
23     head[u] = tot++;
24 }
25 
26 void dfs(int u,int f,int dis,int d[]){
27     d[u]=dis;
28     if( d[u]>d[maxv] ){
29         maxv = u;
30     }
31 
32     for(int i=head[u];~i;i=e[i].nxt){
33         int v=e[i].to;
34         if( v==f ) continue;
35         dfs(v,u,dis+1,d);
36     }
37 }
38 
39 
40 int main()
41 {
42     memset(head,-1,sizeof(head));
43 
44     scanf("%d",&n);
45     rep(i,1,n) scanf("%d",&a[i]);
46 
47     rep(i,1,n-1){
48         int u,v;
49         scanf("%d%d",&u,&v);
50         add(u,v);
51         add(v,u);
52     }
53 
54     int s=1;
55     d1[maxv]=0;
56     dfs(1,-1,0,d1);
57 
58     s=maxv,d1[maxv]=0;
59     dfs(s,-1,0,d1);
60 
61     s=maxv,d2[maxv]=0;
62     dfs(s,-1,0,d2);
63 
64     int maxx=-1;
65     rep(i,1,n){
66         maxx = max(maxx,max(d1[i],d2[i])*a[i]);
67     }
68     printf("%d
",maxx);
69 
70     return 0;
71 }
原文地址:https://www.cnblogs.com/wsy107316/p/12644236.html