[Dfs] [analog network flow] Luogu P4189 Star Trek

Title Description

AD 3000 3 0 0 0 years, the Earth Alliance has captured within the Milky Way N N planet, out of consideration of funds, the government established the only planet in between N-1 N - 1 two-way time tunnel guarantee of any two planets up between each other. Considerations on management, first i i planet requires that each citizen of the Chief Executive within one year shall not exceed the number of planet from the use of space-time tunnel H_i H i times (this statistic is based on the statistics of the number of leave, if you have use left over from the planet H_i H i times, then this year you can no longer use the time tunnel to leave this planet). Louis Paosen is an interstellar traveler, he hopes to use the time tunnel many times as possible, but do not want the planet was eventually forced to settle the conditions too harsh. So he hopes to know for each planet i i, if from 0 starting 0 planet, eventually i i number for the end of the planet, such as Star Trek on the way up to how many times you can use the time tunnel.

 

answer

  • First there is a very good condition, limiting the number of each point are greater than or equal to this degree points, then we can from 0 start D F S over the tree.

     

  • Then two points connected by an edge if a h while > 0 , then go back and forth, then we consider to go from 0 No. nodes go to each node

     

  • If at this time U U of H > 0 , then go directly on it

     

  • If not, then we order from u come to v , must be the last time u v exhumation away removed, they would be v times +1, then if v frequency of a son is not 0 , then one can continue exhumation

 

Code

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #define N 50010
 5 using namespace std;
 6 int head[N],cnt,h[N],ans[N],now,p[N],n;
 7 struct edge{ int from,to; }e[N<<1];
 8 void insert(int u,int v){ e[++cnt].from=head[u];e[cnt].to=v;head[u]=cnt; }
 9 void dfs(int u,int fa)
10 {
11     for (int i=head[u],x,v;i;i=e[i].from)
12         if (e[i].to!=fa)
13         {
14             v=e[i].to,dfs(v,u),x=min(h[u],h[v]);
15             now+=x*2,h[u]-=x,h[v]-=x;
16             if (h[v]) p[u]=v;
17         }
18 }
19 void dfs2(int u,int fa)
20 {
21     ans[u]=now;
22     for (int i=head[u];i;i=e[i].from)
23         if (e[i].to!=fa)
24         {
25             int v=e[i].to;
26             if (h[u]) h[u]--,now++,dfs2(v,u),h[u]++,now--;
27             else if (p[v]) h[p[v]]--,now++,dfs2(v,u),h[p[v]]++,now--; 
28             else h[v]++,now--,dfs2(v,u),h[p[v]]--,now++;    
29         }
30 }
31 int main()
32 {
33     scanf("%d",&n);
34     for (int i=1;i<=n;i++) scanf("%d",&h[i]);
35     for (int i=1,u,v;i<n;i++) scanf("%d%d",&u,&v),u++,v++,insert(u,v),insert(v,u),h[u]--,h[v]--,now+=2;
36     dfs(1,0),dfs2(1,0);
37     for (int i=1;i<=n;i++) printf("%d\n",ans[i]);
38 }

 

Guess you like

Origin www.cnblogs.com/Comfortable/p/11237274.html