zoukankan      html  css  js  c++  java
  • Bzoj 2435: [Noi2011]道路修建 (dfs)

    Bzoj 2435: [Noi2011]道路修建

    大水题,会dfs即可.
    记录一下size,n - size为另一部分的点..
    Bzoj 会爆栈(真坑).
    ans记得开longlong,不然只有10分.

    #include <iostream>
    #include <cstdio>
    const int maxN = 1000000 + 7;
    
    int size[maxN],n; // f[i]表示以i为根的子树大小. len * abs (n - 2 * f[i])
    
    long long ans;
    
    struct Node {
    	int v,nex,w;
    }Map[maxN << 1];
    
    int head[maxN],num;
    
    inline int abs(int a) {return a >= 0 ? a : -a;}
    
    void add_Node(int u,int v,int w) {
    	Map[++ num] = (Node) {v,head[u],w};
    	head[u] = num;
    	return ;
    }
    
    inline int read() {
    	int x = 0,f = 1;char c = getchar();
    	while(c < '0' || c > '9') {if(c == '-')f = -1;c = getchar();}
    	while(c >= '0' && c <= '9') {x = x * 10 + c - '0';c = getchar();}
    	return x * f;
    }
    
    void dfs_1(int now,int fa) {
    	size[now] = 1;
    	for(int i = head[now];i;i = Map[i].nex) {
    		int v = Map[i].v,w = Map[i].w;
    		if(v != fa) {
    			dfs_1(v,now);
    			size[now] += size[v];
    			ans += (long long)w * abs(n - 2 * size[v]);
    		}
    	}
    }
    
    int main() {
    	n = read();
    	for(int i = 1,u,v,w;i < n;++ i) {
    		u = read();v = read();w = read();
    		add_Node(u,v,w);
    		add_Node(v,u,w);
    	}
    	dfs_1(n,n);
    	printf("%lld", ans);
    	return 0;
    }
    
  • 相关阅读:
    Exercice_3.8
    Exercice_3.13.1_练习使用vector2
    Exercice_3.13_练习使用vetor
    Exercice_3.10_去掉string对象中的标点符号
    Exercice_3.7_判断两个字符串的大小和长度
    1-日期时间视图 2-长按事件
    View(视图)2
    View(视图)
    计算器(UI事件)给按钮添加监听器
    Activity(活动)
  • 原文地址:https://www.cnblogs.com/tpgzy/p/9760270.html
Copyright © 2011-2022 走看看