Description
There are n countries on planet W. For the economic development of their respective countries, they decided to
The construction of two-way roads makes connectivity between countries. But the kings of every country are so stingy that they only want to
To build exactly n–1 two-way road. The construction of each road costs a fee equal to the absolute value of the road length multiplied by the number of countries on both sides of the road. For example, in the dotted line, there are 2 or 4 countries at each end of the road, and if the road length is 1, the cost is 1x|2–4|=2. The number in the circle in the figure represents the country's number.
As the number of countries is very large, there are many ways to build roads, while the construction of each of these programmes
Cost is difficult to calculate manually, the king decided to find someone to design a software, for a given construction plan,
To figure out the costs that are required. Please help the Kings design a software like this.
Input
The first line of input contains an integer n, representing the number of countries on planet W, the country from 1 to n
Number. Next n–1 describes road construction, where line I contains three integers ai, bi, and CI, table
The two-way road is constructed between AI and bi two countries with a length of CI.
Output
Output An integer that represents the total cost to build all roads.
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
This is a mock question ...
#include <cstdio> #include <iostream> #include <cstring> #include <cstdlib> #include < algorithm> #include <cmath> #include <queue> #include <deque> #include <set> #include <map > #include <ctime> #define LL long long#define INF 0x7ffffff#define pa pair<int,int> #define Pi 3.1415926535897932384626433832795028841971using namespace Std;inline ll read () {ll x=0,f=1;char Ch=getchar (); while (ch< ' 0 ' | | Ch> ' 9 ') {if (ch== '-') F=-1;ch=getchar ();} while (ch>= ' 0 ' &&ch<= ' 9 ') {x=x*10+ch-' 0 '; Ch=getchar ();} return x*f;} struct Edge{int to,next,v;} E[2000010];struct bian{int x, Y, Z;} B[1000010];int n,m,cnt;int head[1000010];bool mrk[1000010];int fa[1000010];int son[1000010]; LL ans;inline void ins (int u,int v,int W) {e[++cnt].to=v;e[cnt].v=w;e[cnt].next=head[u];head[u]=cnt;} inline void Insert (int u,int v,int W) {ins (u,v,w); ins (v,u,w);} inline void dfs (int x) {if (mrk[x]) return;mrk[x]=1;son[x]=1;for (int i=head[x];i;i=e[i].next) if (!mrk[e[I].to]) {fa[e[i].to]=x; DFS (E[I].TO); SON[X]+=SON[E[I].TO]; }}int Main () {n=read (); for (int i=1;i<n;i++) {b[i].x=read (); B[i].y=read (); B[i].z=read (); Insert (b[i].x,b[i].y,b[i ].Z);} DFS (1), for (int i=1;i<n;i++) {int x=b[i].x,y=b[i].y;if (fa[y]==x) swap (x, y), ans+= (LL) ABS (son[x]-(N-SON[X))) *b[i]. Z;} printf ("%lld\n", ans);}
bzoj2435 [Noi2011] Road construction