hdoj1102 Constructing Roads(Prime || Kruskal)
阿新 • • 發佈:2017-12-03
oot memset tro map truct get print strong 連接
題目鏈接
http://acm.hdu.edu.cn/showproblem.php?pid=1102
題意
有n個村莊(編號1~n),給出n個村莊之間的距離,開始時n個村莊之間已經有了q條路,現在需要修一條路,這條路連接起所有的村莊,求在已經存在的路徑的基礎上,最少還需要修多長的路。
思路
普通最小生成樹是從零開始構造一棵最小生成樹,而這題開始時圖中已經有了一些路徑,那這些路就不需要被修了,所以將這些路的修理長度置為0,然後使用Prime算法或者Kruskal算法求解即可。
代碼
Prime算法:
1 #include <algorithm> 2 #include <cstring> 3#include <cstdio> 4 using namespace std; 5 6 const int INF = 0x7fffffff; 7 const int N = 100 + 10; 8 int map[N][N]; 9 int dist[N]; //記錄從起點到其余各點的長度,不斷更新 10 int n, q; 11 12 void prime() 13 { 14 int min_edge, min_node; 15 for (int i = 1; i <= n; i++) 16 dist[i] = INF;17 int ans = 0; 18 int now = 1; 19 for (int i = 1; i < n;i++) 20 { 21 min_edge = INF; 22 dist[now] = -1; 23 for (int j = 1; j <= n; j++) 24 { 25 if (j != now && dist[j] >= 0) //註意是dist[j]>=0 26 { 27 if(map[now][j] >= 0) 28 dist[j] = min(dist[j], map[now][j]); 29 if (dist[j] < min_edge) 30 { 31 min_edge = dist[j]; ////min_edge存儲與當前結點相連的最短的邊 32 min_node = j; 33 } 34 } 35 } 36 ans += min_edge; ////ans存儲最小生成樹的長度 37 now = min_node; 38 } 39 printf("%d\n", ans); 40 } 41 42 int main() 43 { 44 //freopen("hdoj1102.txt", "r", stdin); 45 while (scanf("%d", &n) == 1) 46 { 47 memset(map, 0, sizeof(map)); 48 for (int i = 1; i <= n;i++) 49 for (int j = 1; j <= n; j++) 50 scanf("%d", &map[i][j]); 51 scanf("%d", &q); 52 int a, b; 53 for (int i = 0; i < q; i++) 54 { 55 scanf("%d%d", &a, &b); 56 map[a][b] = map[b][a] = 0; 57 } 58 prime(); 59 } 60 return 0; 61 }
Kruskal算法:
1 #include <algorithm> 2 #include <cstring> 3 #include <cstdio> 4 #include <vector> 5 using namespace std; 6 7 struct Edge 8 { 9 int a, b, dist; 10 11 Edge() {} 12 Edge(int a, int b, int d) :a(a), b(b), dist(d) {} 13 bool operator < (Edge edge) //將邊按邊長從短到長排序 14 { 15 return dist < edge.dist; 16 } 17 }; 18 19 const int N = 100 + 10; 20 int p[N]; //並查集使用 21 int map[N][N]; 22 vector<Edge> v; 23 int n, q; 24 25 int find_root(int x) 26 { 27 if (p[x] == -1) 28 return x; 29 else return find_root(p[x]); 30 } 31 32 void kruskal() 33 { 34 memset(p, -1, sizeof(p)); 35 sort(v.begin(), v.end()); 36 int ans = 0; 37 for (int i = 0; i < v.size(); i++) 38 { 39 int ra = find_root(v[i].a); 40 int rb = find_root(v[i].b); 41 if (ra != rb) 42 { 43 ans += v[i].dist; 44 p[ra] = rb; 45 } 46 } 47 printf("%d\n", ans); 48 } 49 50 int main() 51 { 52 //freopen("hdoj1102.txt", "r", stdin); 53 while (scanf("%d", &n) == 1) 54 { 55 v.clear(); 56 int t; 57 for (int i = 1; i <= n; i++) 58 for (int j = 1; j <= n; j++) 59 scanf("%d", &map[i][j]); 60 scanf("%d", &q); 61 int a, b; 62 for (int i = 0; i < q; i++) 63 { 64 scanf("%d%d", &a, &b); 65 map[a][b] = map[b][a] = 0; 66 } 67 68 for (int i = 1; i <= n; i++) 69 for (int j = 1; j <= n; j++) 70 if (j > i) v.push_back(Edge(i, j, map[i][j])); 71 72 kruskal(); 73 } 74 return 0; 75 }
註意點
這題是有多組輸入數據的,如果只按一組輸入數據處理的話會WA.
hdoj1102 Constructing Roads(Prime || Kruskal)