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

    xiaoxiao2024-12-30  29

    题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; }
    转载请注明原文地址: https://ju.6miu.com/read-1295152.html
    最新回复(0)