单测试点时限: 1.0 秒
内存限制: 512 MB
有很多城市之间已经建立了路径,但是有些城市之间没有路径联通。为了联通所有的城市,现在需要添加一些路径,为了节约,需要满足添加总路径是最短的。
输入
第一行 333 个整数 n,m,sn, m, sn,m,s, 分别表示城市的数量、已经存在的路的数量、可修的路的数量。
之后的 mmm 行,每行 333 个整数 x,y,dx, y, dx,y,d,表示点 xxx 到点 yyy 有一条长度为 ddd 的已经存在的路径。
之后的 sss 行,每行 333 个整数 x,y,dx, y, dx,y,d,表示点 xxx 到点 yyy 有一条长度为 ddd 的可修的路径。
0<n,m,s,d≤1050<n,m,s,d≤10^50<n,m,s,d≤105 。
输出
输出一个整数表示需要添加的最短的路径长度。
若果无论如何也无法使得所有的城市联通,输出 Concubines can't do it.
。
样例
input
5 3 2
1 2 1
1 3 2
1 4 3
2 3 4
2 5 5
output
5
Solve
最小生成树裸题,前mmm条边的边权变成000,后sss条边的边权不变,进行MST
Code
#include<bits/stdc++.h>
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
const int maxn=1e6+10;
const int maxm=1e3+10;
const int inf=(1<<30);
const ll INF=(1LL*1<<60);
using namespace std;
int f[maxn];
struct Edge
{
int u,v,w;
}edge[maxn];
int tol;
void add(int u,int v,int w)
{
edge[tol].u=u;
edge[tol].v=v;
edge[tol++].w=w;
}
bool cmp(Edge a,Edge b)
{
return a.w<b.w;
}
int Find(int x)
{
if(f[x]==x)
return x;
else
return f[x]=Find(f[x]);
}
ll kru(int n)
{
for(int i=0;i<=n;i++)
f[i]=i;
sort(edge,edge+tol,cmp);
int cnt=0;
ll ans=0;
for(int i=0;i<tol;i++)
{
int u=edge[i].u;
int v=edge[i].v;
int w=edge[i].w;
int tOne=Find(u);
int tTwo=Find(v);
if(tOne!=tTwo)
{
ans+=1LL*w;
f[tOne]=tTwo;
cnt++;
}
}
if(cnt<n-1)
return -1;
else
return ans;
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);
int n,m,s;
cin>>n>>m>>s;
int res=0;
for(int i=0;i<m;i++)
{
int x,y,d;
cin>>x>>y>>d;
res=max(max(x,y),res);
add(x,y,0);
add(y,x,0);
}
int a1=kru(m);
for(int i=0;i<s;i++)
{
int x,y,d;
cin>>x>>y>>d;
add(x,y,d);
add(y,x,d);
}
if(kru(n)==-1)
cout<<"Concubines can't do it."<<endl;
else
cout<<1LL*kru(n)<<endl;
return 0;
}