http://acm.hdu.edu.cn/showproblem.php?pid=1102
题意:n个村庄,给你一个矩阵代表村庄i到j的距离,求要想使所有村庄连通需要修多少长度的路。
思路:基础MST。已经给你的道路相当于这两点已经可达,那么这两点之间就不用修路,赋长度为0,对边方向性的操作同hdu1233。这一点要想清楚,不得不说图论里有些想法真的好神奇。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
using namespace std;
typedef long long LL;
const int N = 505;
const int INF = 0x3f3f3f3f;
int mincost[N], G[N][N], pre[N], n, ednum, sum;
bool vis[N];
struct node
{
int u, v, w;
}edge[N*N];
bool cmp(node x, node y)
{
if(x.w<y.w) return true;
else return false;
}
void prim()
{
for(int i = 1; i <= n; i++)
mincost[i] = G[1][i];//从起点到各个点的花费
memset(vis, false, sizeof(vis));
mincost[1] = 0;
vis[1] = true;
for(int i = 2; i <= n; i++)//起点已访问过。遍历n-1个节点
{
int k = -1, minpath = INF;
for(int j = 1; j <= n; j++)
{
if(!vis[j] && (k==-1 || mincost[j]<minpath))//寻找起点离未访问节点花费最小的点
{
k = j;
minpath = mincost[j];
}
}
if(k == -1) break;//已经遍历所有的点
vis[k] = true;
sum+=minpath;
for(int j = 1; j <= n; j++)//以上面找出花费最小的节点为起点更新其对其他未访问节点的最小花费
{
if(!vis[j]) mincost[j] = min(mincost[j], G[k][j]);
}
}
}
int Find(int x)
{
int r = x;
while(r != pre[r])
r = pre[r];
int i = x, j;
while(pre[i] != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void Union(int p1, int p2, int w)
{
int x = Find(p1);
int y = Find(p2);
if(x != y)
{
pre[x] = y;
sum+=w;
}
}
void kruskal()
{
for(int i = 1; i <= n; i++)
pre[i] = i;
sort(edge+1, edge+1+ednum, cmp);
for(int i = 1; i <= ednum; i++)
{
Union(edge[i].u, edge[i].v, edge[i].w);
}
}
int main()
{
// freopen("in.txt", "r", stdin);
int u, v;
while(~scanf("%d", &n))
{
sum = 0;
ednum = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
scanf("%d", &G[i][j]);
edge[++ednum] = (struct node){i, j, G[i][j]};
}
int q;
scanf("%d", &q);
for(int i = 1; i <= q; i++)
{
scanf("%d%d", &u, &v);
G[u][v] = G[v][u] = 0;
edge[++ednum] = (struct node){u, v, 0};
// edge[++ednum] = (struct node){v, u, 0};
}
// prim();
kruskal();
printf("%d\n", sum);
}
return 0;
}