练习四 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;
}
}
}
}
思路:这是最小生成树问题,我采用的是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;
}
}
}
}
相关文章推荐
- 详解图的应用(最小生成树、拓扑排序、关键路径、最短路径)
- 最小生成树算法之Prim算法
- 使用C语言实现最小生成树求解的简单方法
- 最小生成树算法——Prim和Kruskal算法的实现
- 初学图论-Kahn拓扑排序算法(Kahn's Topological Sort Algorithm)
- 初学图论-Bellman-Ford单源最短路径算法
- 初学图论-DAG单源最短路径算法
- 初学图论-Dijkstra单源最短路径算法
- 初学图论-Dijkstra单源最短路径算法基于优先级队列(Priority Queue)的实现
- Data Structure - Week 15
- 封装好的Folyd建图,C++源码
- LCA模板
- 图论学习笔记之一——Floyd算法
- poj 2485 Highways
- HDU1301 最小生成树kruskal裸题
- 【LCA】SPOJ QTREE2
- poj 3249 Test for Job 最长路
- Kruskal 最小生成树
- 最小生成树
- 一笔画探索