【DP】hdu4714树形DP,用c++交别用g++交

http://acm.hdu.edu.cn/showproblem.php?pid=4714

题意:
给你一颗n个节点的树,你可以删除或者添加一些边,代价都是1。问:要把这棵树变成一个环,至少需要多少代价?

对于一颗树(子树),如果他的儿子数超过1,则需要改动,,
如果他有父亲节点,那么代价是(son-2)*2(先拆再连),将这颗子树变成一个链
如果这个点是root,代价是(son-1)*2,(画图脑补)
最后改完后再把首位一连(ans++)

如果你MLE或者爆栈的话死活调不过的话
把g++改成c++试试
这里写图片描述
我也不知道为什么,,,,
当时内心已经接近崩溃了

#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
const int N=1000007;
int ans;
vector<int>g[N];

int dfs(int rt,int fa){
    //printf("dfs(%d,%d):\n",rt,fa);
    int son = 0;
    for (int i=0;i<g[rt].size();i++){
        int x = g[rt][i];
        if (x==fa)continue;
        son += dfs(x,rt);
    }
    if (son>=2){
        if (rt==1) ans += (son-2)<<1;
        else ans += (son-1)<<1;
        return 0;
    }
    return 1;
}

int main(){
    //freopen("fuck.in","r",stdin);
    int T,x,y,n;
    scanf("%d",&T);
    while (T--){
        scanf("%d",&n);
        for (int i=1;i<=n;i++)g[i].clear();
        for (int i=1;i<n;i++){
            scanf("%d%d",&x,&y);
            g[x].push_back(y);
            g[y].push_back(x);
        }
        ans = 0;
        dfs(1,-1);
        printf("%d\n",ans+1);
    }
    return 0;
}
posted @ 2016-08-13 19:30  伟大的蚊子  阅读(72)  评论(0编辑  收藏  举报