zoukankan      html  css  js  c++  java
  • 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):
    ",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
    ",ans+1);
        }
        return 0;
    }
    
  • 相关阅读:
    windows10安装pycharm,以及pycharm教程和破解码
    windows 10安装python3和python2
    Git之仓库管理
    Python操作 Excel表格
    ansible 基础操作
    Flask-Migrate
    flask-script
    flask-sqlalchemy
    基于数字证书的二次登录认证流程
    摘录:识别系统原理(转)
  • 原文地址:https://www.cnblogs.com/cww97/p/7533983.html
Copyright © 2011-2022 走看看