POJ 1251 Jungle Roads
Description:
The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.
9 A 2 B 12 I 25 B 3 C 10 H 40 I 8 C 2 D 18 G 55 D 1 E 44 E 2 F 60 G 38 F 0 G 1 H 35 H 1 I 35 3 A 2 B 10 C 40 B 1 C 20 0Sample Output
216 30
题目大意:
题目描述奇长无比, 实际上是个水题。 意思是说有n个村庄, 每个村庄通往另一个村庄的路都坏了但是修路又很贵,所以现在要用最小的花费去修往所有村庄互通的路(没有回环)。
解题思路:
裸的最小生成树的板子题, 注意一点就是每个端点是字符类型用prim更好写一些,比较坑的是我一开始用getchar()疯狂RE至今不知为何(ubuntu16.04 codeblocks16.01, gets()必然是不能用的毕竟已经逐出环境了)。
代码:
#include <iostream>
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
using namespace std;
/*
*ios::sync_with_stdio(false);
*/
typedef long long ll;
typedef unsigned long long ull;
const int dir[5][2] = {0, 1, 0, -1, 1, 0, -1, 0, 0, 0};
const ll ll_inf = 0x7fffffff;
const int inf = 0x3f3f3f;
const int mod = 1000000;
const int Max = 9999;
int Map[33][33], dis[33];
bool vis[33];
int n, num, cnt, ans;
void Init() {
for (int i = 0; i < 27; ++i) {
vis[i] = 0;
for (int j = i; j < 27; ++j) {
Map[i][j] = Map[j][i] = (i == j) ? 0 : inf;
}
}
}
void Prim(){
int ans = 0, minx, mark;
for(int i = 0; i < n; i++)
dis[i] = Map[1][i];
for(int i = 0; i < n; i++){
minx = inf;
for(int j = 0; j < n; j++)
if(!vis[j] && minx > dis[j])
minx = dis[mark = j];
if(minx == inf) break;
vis[mark] = 1;
ans += minx;
for(int j = 0; j < n; j++)
if(!vis[j])
dis[j] = min(dis[j], Map[mark][j]);
}
printf("%d\n", ans);
}
int main() {
// definition
int x, y;
// initialization
//freopen("input.txt", "r", stdin);
while (scanf("%d", &n) && n) {
Init();
for (int i = 0; i < n - 1; ++i) {
char ch, tt;
scanf("\n%c %d",&ch, &num);
for (int j = 0; j < num; ++j) {
char temp;
int wi;
scanf(" %c %d", &temp, &wi);
// u, v
x = ch - 'A';
y = temp - 'A';
if (Map[x][y] > wi) Map[x][y] = Map[y][x] = wi;
}
}
Prim();
}
return 0;
}