zoj 1406 - Jungle Roads

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1406

这道题让我见识了什么叫做坑跌。。。。用c输入的时候一定要注意格式,我因为输入格式没控制好,导致一直以为算法错了,调了一个多小时。。。用c++貌似好的多,没有神马空格换行的困扰,看来以后碰到格式复杂的输入可以考虑用c++的流。。。。

代码如下:

prim

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define INT_MAX 66666

int N;
int arcs[30][30];
int path[30];
int flag[30];

int mincost()
{
int i, min, besti;
min = INT_MAX;
for(i = 0; i < N; i++)
{
if(!flag[i] && path[i] < min)
{
min = path[i];
besti = i;
}
}
return besti;
}

int main()
{
int i, j, n, dis, cost, k;
char c1, c2;
while(scanf("%d", &N) && N)
{
getchar();
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
arcs[i][j] = INT_MAX;
arcs[i][i] = 0;
}
for(i = 0; i < N-1; i++)
{
scanf("%c %d", &c1, &n);
if(n)
getchar();
while(n--)
{
scanf("%c %d", &c2, &dis);
arcs[c1-'A'][c2-'A'] = dis;
arcs[c2-'A'][c1-'A'] = dis;
if(n)
getchar();
}
getchar();
}
memset(flag, 0, sizeof(flag));
cost = 0;
for(i = 0; i < N; i++)
path[i] = arcs[0][i];
flag[0] = 1;
for(i = 0; i < N-1; i++)
{
k = mincost();
flag[k] = 1;
cost += path[k];
for(j = 0; j < N; j++)
{
if(!flag[j] && arcs[k][j] < INT_MAX && arcs[k][j] < path[j])
path[j] = arcs[k][j];
}
}
printf("%d\n", cost);
/*for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
printf("%-5d ", arcs[i][j]);
putchar(10);
}
*/
}
return 0;
}

克鲁斯卡尔(并查集)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int N;
int u[100], v[100], w[100];
int fa[30];
int r[100];

int find(int x)
{
if(x == fa[x])
return x;
return fa[x] = find(fa[x]);
}

int cmp(const int i, const int j)
{
return w[i] < w[j];
}

int main()
{
int i, n, cost, dis, num, x, y;
char c1, c2;
while(scanf("%d", &N) && N)
{
getchar();
num = 0;
for(i = 0; i < N-1; i++)
{
scanf("%c %d", &c1, &n);
if(n)
getchar();
while(n--)
{
scanf("%c %d", &c2, &dis);
u[num] = c1 - 'A';
v[num] = c2 - 'A';
w[num] = dis;
num++;
if(n)
getchar();
}
getchar();
}
cost = 0;
for(i = 0; i < N; i++)
fa[i] = i;
for(i = 0; i < num; i++)
r[i] = i;
sort(r, r+num, cmp);
for(i = 0; i < num; i++)
{
x = find(u[r[i]]);
y = find(v[r[i]]);
if(x != y)
{
cost += w[r[i]];
fa[x] = y;
}
}
printf("%d\n", cost);
}
return 0;
}



你可能感兴趣的:(ZOJ)