NOI2011道路修建

2435: [Noi2011]道路修建

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 1974  Solved: 550
[Submit][Status]

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

Day2

题解:

没见过这么送分的

貌似2011年是我见过送分最多的年份了  day1t1 75 day2t1100  怪不得那年铜牌线 300

再加上阿狸的打字机,用kmp大概能骗到20分……

随机选择一个节点(random),将无根树转为有根树,从下向上遍历,直接更新答案和父节点的信息 just so

这个规模据说会爆栈……果然,cena爆了11个点,不过linux下应该是无压力AC吧……

代码:

 1 const maxn=1000000+10;
 2 type node=record
 3      from,go,next,w:int64;
 4      end;
 5 var ans:int64;
 6     e:array[0..2*maxn] of node;
 7     head,s:array[0..maxn] of int64;
 8     v:array[0..maxn] of boolean;
 9     i,n,x,y,z,root,tot:longint;
10 procedure ins(x,y,z:longint);
11  begin
12  inc(tot);
13  e[tot].from:=x;e[tot].w:=z;e[tot].go:=y;e[tot].next:=head[x];head[x]:=tot;
14  end;
15 procedure insert(x,y,z:longint);
16  begin
17  ins(x,y,z);ins(y,x,z);
18  end;
19 procedure init;
20  begin
21  readln(n);
22  for i:=1 to n-1 do begin readln(x,y,z);insert(x,y,z);end;
23  end;
24 procedure dfs(x:longint);
25  var i,y:longint;
26  begin
27  s[x]:=0;
28  v[x]:=true;
29  i:=head[x];
30  while i<>0 do
31   begin
32   y:=e[i].go;
33   if not(v[y]) then
34    begin
35     dfs(y);
36     inc(s[x],s[y]);
37     inc(ans,e[i].w*(abs(s[y]-(n-s[y]))));
38    end;
39   i:=e[i].next;
40   end;
41  inc(s[x]);
42  end;
43 procedure main;
44  begin
45  randomize;
46  ans:=0;
47  root:=random(n)+1;
48  fillchar(v,sizeof(v),false);
49  dfs(root);
50  writeln(ans);
51  end;
52 begin
53  assign(input,'road.in');assign(output,'road.out');
54  reset(input);rewrite(output);
55  init;
56  main;
57  close(input);close(output);
58 end.    
View Code
原文地址:https://www.cnblogs.com/zyfzyf/p/3850763.html