小胖守皇宫!
又双叒叕水了一篇
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int n,m,cnt,ans; 6 int fa[200005]; 7 int dep[200005]; 8 int dp[200005][3]; 9 int head[200005]; 10 struct Edge{ 11 int fr; 12 int to; 13 int nxt; 14 }edge[400005]; 15 void init(){ 16 memset(head,-1,sizeof(head)); 17 } 18 void addedge(int f,int t){ 19 cnt++; 20 edge[cnt].fr=f; 21 edge[cnt].to=t; 22 edge[cnt].nxt=head[f]; 23 head[f]=cnt; 24 } 25 void dfs(int u){ 26 int tmp=0x3f3f3f3f; 27 for(int i=head[u];i!=-1;i=edge[i].nxt){ 28 int v=edge[i].to; 29 if(v==fa[u])continue; 30 fa[v]=u;dep[v]=dep[u]+1; 31 dfs(v); 32 dp[u][1]+=min(dp[v][0],min(dp[v][2],dp[v][1])); 33 dp[u][2]+=min(dp[v][2],dp[v][1]); 34 tmp=min(dp[v][1]-dp[v][2],tmp); 35 dp[u][0]+=min(dp[v][1],dp[v][2]); 36 } 37 if(tmp>0)dp[u][2]+=tmp; 38 if(dep[u]>1)dp[u][1]+=1; 39 } 40 int main(){ 41 init(); 42 scanf("%d",&n); 43 for(int i=1;i<n;i++){ 44 int u,v; 45 scanf("%d%d",&u,&v); 46 addedge(u,v); 47 addedge(v,u); 48 } 49 dfs(1); 50 printf("%d\n",dp[1][1]); 51 return 0; 52 }
原文地址:https://www.cnblogs.com/lnxcj/p/9874018.html
时间: 2024-10-09 01:31:07