某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了有可能建设成快速路的若干条道路的成本,求畅通工程需要的最低成本。

输入格式:

输入的第一行给出城镇数目N (1<N≤1000)和候选道路数目M≤3N;随后的M行,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号(从1编号到N)以及该道路改建的预算成本。

输出格式:

输出畅通工程需要的最低成本。如果输入数据不足以保证畅通,则输出“Impossible”。

输入样例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3结尾无空行

输出样例1:

1
2
3
4
5
12



结尾无空行

输入样例2:

1
2
3
4
5
5 4
1 2 1
2 3 2
3 1 3
4 5 4

输出样例2:

1
Impossible

思路

prim

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
using namespace std;
const int maxn=1000+5;
const int inf=1e9;
//最小生成树
//prim
int G[maxn][maxn];
int vis[maxn];
int lowcost[maxn];

int n,e;

int prim(int v)
{
int res=0;
vis[v]=1;
for(int i =1 ;i<=n;++i)
{
if(G[i][v]<inf)
lowcost[i]=G[i][v];
else
lowcost[i]=inf;
}
for(int cnt =0;cnt<n-1;++cnt)
{
int low=inf;
int idx=0;
for(int i=1;i<=n;++i)
{
if(!vis[i]&&lowcost[i]<low)
{
low=lowcost[i];
idx=i;
}
}
res+=low;

if(idx==0) return -1;//不连通

vis[idx]=1;
for(int i =1;i<=n;++i)
{
if(!vis[i]&&G[i][idx]<lowcost[i])
lowcost[i]=G[i][idx];
}
}
return res;
}
int main()
{
for(int i=0;i<maxn;++i) for(int j=0;j<maxn;++j) G[i][j]=inf;

cin>>n>>e;
while(e--)
{
int a,b,c;
cin>>a>>b>>c;
G[a][b]=G[b][a]=c;
}
int ans=prim(1);
if(ans==-1) cout<<"Impossible";
else cout<<ans;
}