zoukankan      html  css  js  c++  java
  • bzoj 2435 道路修建

    Written with StackEdit.

    Description

    (W) 星球上有 (n) 个国家。为了各自国家的经济发展,他们决定在各个国家 之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿意修建恰好 (n – 1)条双向道路。 每条道路的修建都要付出一定的费用, 这个费用等于道路长度乘以道路两端的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 (2) 个、(4)个国家,如果该道路长度为 (1),则费用为(1×|2 – 4|=2)。图中圆圈里的数字表示国家的编号。


    由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建
    费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计 算出所需要的费用。请你帮助国王们设计一个这样的软件。

    Input

    输入的第一行包含一个整数(n),表示 (W) 星球上的国家的数量,国家从 (1)(n)
    编号。接下来 (n – 1)行描述道路建设情况,其中第 (i) 行包含三个整数(a _i、b_i)(c_i),表示第(i) 条双向道路修建在 (a_i)(b_i)两个国家之间,长度为(c_i)

    Output

    输出一个整数,表示修建所有道路所需要的总费用。

    Sample Input

    6
    1 2 1
    1 3 1
    1 4 2
    6 3 1
    5 2 1

    Sample Output

    20

    HINT

    (n = 1000000, 1≤a_i, b_i≤n.)

    (0 ≤ci≤ 10^6.)

    Solution

    • 题意十分不明确...
    • 应该是直接问每条边权值*两边节点数差,和"修建"无关.
    • 记录子树大小(siz).
    • 显然每条边贡献为(val[u,v]*abs(n-2size[e.u])).
    #include<bits/stdc++.h>
    using namespace std;
    typedef long long LoveLive;
    inline int read()
    {
    	int out=0,fh=1;
    	char jp=getchar();
    	while ((jp>'9'||jp<'0')&&jp!='-')
    		jp=getchar();
    	if (jp=='-')
    		{
    			fh=-1;
    			jp=getchar();
    		}
    	while (jp>='0'&&jp<='9')
    		{
    			out=out*10+jp-'0';
    			jp=getchar();
    		}
    	return out*fh;
    }
    const int MAXN=1e6+10;
    int cnt=0,head[MAXN];
    int nx[MAXN<<1],to[MAXN<<1],val[MAXN<<1];
    int siz[MAXN];
    inline void add(int u,int v,int w)
    {
    	++cnt;
    	to[cnt]=v;
    	nx[cnt]=head[u];
    	val[cnt]=w;
    	head[u]=cnt;
    }
    int n;
    LoveLive ans=0;
    void dfs(int u,int fa)
    {
    	siz[u]=1;
    	for(int i=head[u];i;i=nx[i])
    		{
    			int v=to[i];
    			if(v==fa)
    				continue;
    			dfs(v,u);
    			ans+=1LL*abs(n-siz[v]*2)*val[i];
    			siz[u]+=siz[v];
    		}
    }
    int main()
    {
    	n=read();
    	for(int i=1;i<n;++i)
    		{
    			int u=read(),v=read(),w=read();
    			add(u,v,w);
    			add(v,u,w);
    		}
    	dfs(1,0);
    	printf("%lld
    ",ans);
    	return 0;
    }
    
  • 相关阅读:
    ACM 人见人爱A^B
    ACM Max Factor
    ACM Primes
    ACM Least Common Multiple
    ACM 最小公倍数
    ACM Bone Collector
    ACM 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活
    ACM Piggy Bank
    ACM 饭卡
    ACM Where is the Marble?
  • 原文地址:https://www.cnblogs.com/jklover/p/10037729.html
Copyright © 2011-2022 走看看