标签:struct nbsp 节点 ble dep pen inpu 输出 mmm
第1行:2个数N, K中间用空格分隔(1<= N <= 100000, 0 <= K <= N)。 之后N-1行:每行2个数S, E中间用空格分隔,表示编号为S的村庄同编号为E的村庄之间有道路相连。(0 <= S, E < N)。
输出一个数说明要实现对全部村庄的武力控制,夹克老爷需要派出最少多少名家丁?
4 1 0 1 0 2 0 3
1
1 #include<stdio.h> 2 #include<iostream> 3 #define maxn 1000000 4 using namespace std; 5 6 int DP[maxn][5],buoy[maxn],anch[maxn],depth[maxn],sz[maxn],n,k; 7 8 struct edge{ 9 int from,v; 10 }e[maxn*2]; int tot,first[maxn]; 11 void insert(int u,int v){ tot++; e[tot].from = first[u]; e[tot].v = v; first[u] = tot; } 12 13 void dfs(int u,int pre){ 14 int sum = 0; sz[u] = 1; 15 DP[u][0] = DP[u][1] = 0; buoy[u] = 1e9; anch[u] = -1e9; 16 for(int i = first[u];i;i = e[i].from){ 17 int v = e[i].v; if(v == pre) continue; 18 depth[v] = depth[u]+1; 19 dfs(v,u); 20 sz[u] += sz[v]; 21 buoy[u] = min(buoy[u],buoy[v]); 22 anch[u] = max(anch[u],anch[v]); 23 sum += DP[v][0]; 24 } 25 26 if(sz[u] == 1){ 27 DP[u][1] = 1; 28 DP[u][0] = 0; 29 if(!k) DP[u][0] = 1; 30 buoy[u] = anch[u] = depth[u]; 31 return; 32 } 33 34 // printf("#%d: buoy%d anch%d\n",u,buoy[u],anch[u]); 35 if(anch[u]-depth[u] >= k){ // Must set 36 // printf("#%d: Poi A\n",u); 37 DP[u][0] = DP[u][1] = sum+1; 38 buoy[u] = depth[u]-k; 39 anch[u] = buoy[u]-1; 40 }else if(2*depth[u]-buoy[u] < anch[u]){ // Can choose 41 // printf("#%d: Poi B\n",u); 42 DP[u][0] = sum; 43 DP[u][1] = sum+1; 44 }else{ // Needn‘t 45 // printf("#%d: Poi C\n",u); 46 DP[u][0] = DP[u][1] = sum; 47 anch[u] = buoy[u]-1; 48 } 49 } 50 51 int main(){ 52 scanf("%d%d",&n,&k); 53 54 for(int i = 1;i < n;i++){ 55 int u,v; scanf("%d%d",&u,&v); 56 u++,v++; insert(u,v); insert(v,u); 57 }depth[1] = 1; 58 59 dfs(1,1); 60 61 printf("%d\n",DP[1][1]); 62 63 // for(int i = 1;i <= n;i++){ 64 // printf("#%d: 0:%d 1:%d buoy:%d anch:%d\n",i,DP[i][0],DP[i][1],buoy[i],anch[i]); 65 // } 66 67 return 0; 68 }
标签:struct nbsp 节点 ble dep pen inpu 输出 mmm
原文地址:http://www.cnblogs.com/Chorolop/p/7779697.html