E. Minimum Spanning Tree
time limit per test
2.0 s
memory limit per test
512 MB
input
standard input
output
standard output
In the mathematical discipline of graph theory, the line graph of a simple undirected weighted graph GG is another simple undirected weighted graph L(G)L(G) that represents the adjacency between every two edges in GG.
Precisely speaking, for an undirected weighted graph GG without loops or multiple edges, its line graph L(G)L(G) is a graph such that:
- Each vertex of L(G)L(G) represents an edge of GG.
- Two vertices of L(G)L(G) are adjacent if and only if their corresponding edges share a common endpoint in GG, and the weight of such edge between this two vertices is the sum of their corresponding edges' weight.
A minimum spanning tree(MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. That is, it is a spanning tree whose sum of edge weights is as small as possible.
Given a tree GG, please write a program to find the minimum spanning tree of L(G)L(G).
Input
The first line of the input contains an integer T(1≤T≤1000)T(1≤T≤1000), denoting the number of test cases.
In each test case, there is one integer n(2≤n≤100000)n(2≤n≤100000) in the first line, denoting the number of vertices of GG.
For the next n−1n−1 lines, each line contains three integers u,v,w(1≤u,v≤n,u≠v,1≤w≤109)u,v,w(1≤u,v≤n,u≠v,1≤w≤109), denoting a bidirectional edge between vertex uuand vv with weight ww.
It is guaranteed that ∑n≤106∑n≤106.
Output
For each test case, print a single line containing an integer, denoting the sum of all the edges' weight of MST(L(G))MST(L(G)).
Example
input
Copy
2
4
1 2 1
2 3 2
3 4 3
4
1 2 1
1 3 1
1 4 1
output
Copy
8
4
本题比普通的最小生成树算法简单的多
仔细观察就可以发现对于每个入度大于2的点 我们只需要在他的所有度中取du-1 个伪边作为贡献
那么我们贪心的取就可以了
-----------------------------------------
变形之后的图 边会变成点 对于每个度数为一的点 和他相连的边自然会是叶子节点 所以不必考虑
而度数为2以上的点 和他相邻的边我们则需要 度数-1 条变形后的边才能 将他们连接 那么贪心的取就行了
补发代码
#include<bits/stdc++.h>
using namespace std;
vector<long long> du[100005];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
long long ans=0;
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
du[i].clear();
}
for(int i=1;i<n;i++)
{
int temp1,temp2;
long long temp3;
scanf("%d%d%lld",&temp1,&temp2,&temp3);
du[temp1].push_back(temp3);
du[temp2].push_back(temp3);
}
for(int i=1;i<=n;i++)
{
sort(du[i].begin(),du[i].end());
}
for(int i=1;i<=n;i++)
{
if(du[i].size()>1)
{
for(int j=0;j<du[i].size();j++)
{
if(j==0)
{
ans+=du[i][0]*(1LL*du[i].size()-1);
}
else
{
ans+=du[i][j];
}
}
}
}
printf("%lld
",ans);
}
}