题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=4714
题意:给你N个点N-1条边,形成一个树,让你拆树,并连接成一个环,每拆一次,连接一次,消耗1,问最小消耗多少
题解:仔细分析,其实就是将每条边变成线段,以最优的方案拆,能拆就拆,其实只能算贪心,
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #pragma comment(linker,"/STACK:102400000,102400000") 3 #define FFC(i,a,b) for(int i=a;i<=b;i++) 4 5 const int maxn=1000010; 6 int v[2*maxn],nxt[2*maxn],g[maxn],ed,ans; 7 8 inline void adg(int x,int y){v[++ed]=y,nxt[ed]=g[x],g[x]=ed;} 9 10 int fuck(int o,int pre){ 11 int sum=0;//统计子结点的个数,已经拆解成线段的不计 12 for(int i=g[o];i;i=nxt[i])if(v[i]!=pre)sum+=fuck(v[i],o); 13 if(sum>1){//如果是树根,就2*(sum-2) 14 if(o==1)ans+=2*(sum-2);else ans+=2*(sum-1); 15 return 0; 16 }else return 1; 17 } 18 19 int main(){ 20 int t,n,i,a,b; 21 scanf("%d",&t); 22 while(t--){ 23 scanf("%d",&n); 24 for(i=ed=ans=0;i<=n;i++)g[i]=0; 25 FFC(i,1,n-1)scanf("%d%d",&a,&b),adg(a,b),adg(b,a); 26 fuck(1,0); 27 printf("%d ",ans+1); 28 } 29 return 0; 30 }