您的位置:首页 > 其它

练习四 1001

2016-06-14 21:18 447 查看
概述:给你一些城镇,以及各个镇之间的距离,现在要修建道路,把这些镇子穿起来,已知一些镇子之间已经有了道路(即不用再修了),现在求施工的最短路径。

思路:这是最小生成树问题,我采用的是kruskal算法。

感想:“一些镇子之间已经有了道路”这个条件比较难缠,想了一会才明白,只要另这些镇子的距离为0就可以,这样就不会影响结果。

#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 105;
int father
;
int map

;
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
struct edge
{
int x, y, v;
}e[N*(N - 1) / 2];
int cmp(edge e1, edge e2)
{
return e1.v<e2.v;
}

int main()
{
//ifstream cin("aaa.txt");
int n;
cin >> n;
int ansa = n;
for (int i = 0; i <= n; ++i)
father[i] = i;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
cin >> map[i][j];
int q;
cin >> q;
int temp1, temp2;
for (int i = 0; i < q; ++i)
{
cin >> temp1 >> temp2;
map[temp1 - 1][temp2 - 1] = 0;
}
int cnt = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
{
e[cnt].x = i;
e[cnt].y = j;
e[cnt].v = map[i][j];
++cnt;
}

int ans = 0;
sort(e, e + cnt, cmp);
for (int i = 0; i < cnt; ++i)
{
int x = find(e[i].x);
int y = find(e[i].y);
if (x != y)
{
ans += e[i].v;
father[x] = y;
--ansa;
if(ansa==1)
{
cout << ans << endl;
return 0;
}

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息