简单的最小生成树问题,关键在于建图的正确性。
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int SIZE = 110;
struct node
{
int u, v, w;
}edge[SIZE*SIZE];
int p[SIZE];
int find(int x)
{
return p[x] == x? x : p[x] = find(p[x]);
}
int cmp(const node a, const node b)
{
return a.w <= b.w;
}
int Kruskal(int n, int m)
{
int ans = 0;
sort(edge, edge+m, cmp);
for(int i = 0; i < m; i++)
{
int x = find(edge[i].u);
int y = find(edge[i].v);
if(x != y)
{
ans += edge[i].w;
p[x] = y;
}
}
return ans;
}
int main()
{
int n, m, t;
int k;
int i, j;
int a, b, c;
while(~scanf("%d", &n))
{
m = 0;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
scanf("%d", &c);
if(i <= j) continue;
edge[m].v = i;
edge[m].u = j;
edge[m].w = c;
m++;
}
}
for(i = 1; i <= n; i++) p[i] = i;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &a, &b);
i = find(a);
j = find(b);
p[i] = j;
}
printf("%d\n", Kruskal(n, m));
}
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int SIZE = 110;
struct node
{
int u, v, w;
}edge[SIZE*SIZE];
int p[SIZE];
int find(int x)
{
return p[x] == x? x : p[x] = find(p[x]);
}
int cmp(const node a, const node b)
{
return a.w <= b.w;
}
int Kruskal(int n, int m)
{
int ans = 0;
sort(edge, edge+m, cmp);
for(int i = 0; i < m; i++)
{
int x = find(edge[i].u);
int y = find(edge[i].v);
if(x != y)
{
ans += edge[i].w;
p[x] = y;
}
}
return ans;
}
int main()
{
int n, m, t;
int k;
int i, j;
int a, b, c;
while(~scanf("%d", &n))
{
m = 0;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
scanf("%d", &c);
if(i <= j) continue;
edge[m].v = i;
edge[m].u = j;
edge[m].w = c;
m++;
}
}
for(i = 1; i <= n; i++) p[i] = i;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &a, &b);
i = find(a);
j = find(b);
p[i] = j;
}
printf("%d\n", Kruskal(n, m));
}
}