NOI的水题...直接一遍DFS即可

-------------------------------------------------------------------------

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<cctype>
 
using namespace std;
 
typedef long long ll;
 
const int maxn = 1000009;
 
inline int read() {
char c = getchar();
int ret = 0;
for(; !isdigit(c); c = getchar());
for(; isdigit(c); c = getchar()) ret = ret * 10 + c - '0';
return ret;
}
 
struct edge {
int to, w;
edge* next;
} E[maxn << 1], *pt = E, *head[maxn];
 
void add(int u, int v, int w) {
pt->to = v; pt->w = w; pt->next = head[u]; head[u] = pt++;
}
void addedge(int u, int v, int w) {
add(u, v, w); add(v, u, w);
}
 
int N, size[maxn];
ll ans = 0;
 
void dfs(int x, int fa = -1) {
size[x] = 1;
for(edge* e = head[x]; e; e = e->next) if(e->to != fa) {
dfs(e->to, x);
size[x] += size[e->to];
ans += ll(e->w) * abs(N - (size[e->to] << 1));
}
}
 
int main() {
N = read();
for(int i = 1; i < N; i++) {
int u = read() - 1, v = read() - 1, w = read();
addedge(u, v, w);
}
dfs(0);
printf("%lld\n", ans);
return 0;
}

-------------------------------------------------------------------------

2435: [Noi2011]道路修建

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 2804  Solved: 869
[Submit][Status][Discuss]

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

Source

最新文章

  1. offsetLeft和style.left的区别
  2. Debian上安装Apache+Django全过程
  3. PHP面试题集
  4. 2015/09/09夜晚js继续学习
  5. Orchard官方文档翻译(六) 建立你的第一个Orchartd站点
  6. HDU1025:Constructing Roads In JGShining&#39;s Kingdom(LIS)
  7. SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-006- 使用thymeleaf(TemplateResolver、SpringTemplateEngine、ThymeleafViewResolver、th:include、th:object、th:field=&quot;*{firstName}&quot;)
  8. 浅析ARP协议及ARP攻击
  9. JS复习:第二十章
  10. Trouble Shooting
  11. AndroidManifest.xml file missing 解决方案
  12. 为Android增加硬件抽象层(HAL)模块访问Linux内核驱动程序
  13. salesforce 得到下拉列表控制依赖值的方法
  14. Unity 大中华区核心业务
  15. Springboot的异常处理与自定义异常
  16. 4558: [JLoi2016]方
  17. Linux rpm命令详解
  18. Go语言环境安装详细介绍
  19. holoeverywhere修改actionbar背景
  20. WINCC runtime连接SIMOTION simulator SIMOSIM

热门文章

  1. BZOJ 1218: [HNOI2003]激光炸弹( 前缀和 + 枚举 )
  2. cocos2d-x中的CCScrollView滑动体验不佳
  3. RAW模板开发--入口文件官方规范
  4. [LeetCode]题解(python):084-Largest Rectangle in Histogram
  5. Android手机安全软件的恶意程序检测靠谱吗--LBE安全大师、腾讯手机管家、360手机卫士恶意软件检测方法研究
  6. 1_HelloWorld
  7. Xamarin几十篇博客,roslyn和dotnet也开源了
  8. 快速注册Uber司机,兼职月入轻松过万
  9. swift3.0 hello swift(1)
  10. Struts2详解