zoukankan      html  css  js  c++  java
  • [NOI 2011]道路修建

    Description

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


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

    Input

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

    Output

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

    Sample Input

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

    Sample Output

    20

    HINT

    n = 1,000,000 1≤ai, bi≤n
    0 ≤ci≤ 10^6

    题解

    日常刷水题...$dfs$记录子树$size$就可以了。

     1 //It is made by Awson on 2017.10.26
     2 #include <set>
     3 #include <map>
     4 #include <cmath>
     5 #include <ctime>
     6 #include <cmath>
     7 #include <stack>
     8 #include <queue>
     9 #include <vector>
    10 #include <string>
    11 #include <cstdio>
    12 #include <cstdlib>
    13 #include <cstring>
    14 #include <iostream>
    15 #include <algorithm>
    16 #define LL long long
    17 #define Min(a, b) ((a) < (b) ? (a) : (b))
    18 #define Max(a, b) ((a) > (b) ? (a) : (b))
    19 #define Abs(a) ((a) < 0 ? (-(a)) : (a))
    20 using namespace std;
    21 const int N = 1e6;
    22 
    23 int n, u, v, c;
    24 struct tt {
    25   int to, next, cost;
    26 }edge[(N<<1)+5];
    27 int path[N+5], top;
    28 int size[N+5];
    29 LL ans;
    30 
    31 void add(int u, int v, int c) {
    32   edge[++top].to = v;
    33   edge[top].cost = c;
    34   edge[top].next = path[u];
    35   path[u] = top;
    36 }
    37 void dfs(int u, int fa) {
    38   size[u] = 1;
    39   for (int i = path[u]; i; i = edge[i].next)
    40     if (edge[i].to != fa) {
    41       dfs(edge[i].to, u);
    42       size[u] += size[edge[i].to];
    43       ans += (LL)edge[i].cost*Abs((n-size[edge[i].to])-size[edge[i].to]);
    44   }
    45 }
    46 void work() {
    47   scanf("%d", &n);
    48   for (int i = 1; i < n; i++) {
    49     scanf("%d%d%d", &u, &v, &c);
    50     add(u, v, c); add(v, u, c);
    51   }
    52   dfs(1, 0);
    53   printf("%lld
    ", ans);
    54 }
    55 int main() {
    56   work();
    57   return 0;
    58 }
  • 相关阅读:
    国王游戏
    选数
    双塔
    线段树
    树状数组及其他特别简单的扩展
    折半搜索
    VUE项目
    git_基本使用
    同源
    axios-使用
  • 原文地址:https://www.cnblogs.com/NaVi-Awson/p/7735046.html
Copyright © 2011-2022 走看看