Light OJ 1040 - Donation(最小生成树)
题目链接
http://www.lightoj.com/volume_showproblem.php?problem=1040
题目大意
初始有一个矩阵,代表从i到j需要花费的电缆数,现在问如果将从1到n全部连接起来,最多剩下多少电缆
解题思路
最小生成树模版题
代码如下
prime算法
#include<bits/stdc++.h>
using namespace std;
const int N = 57;
const int INF = 0x3f3f3f3f;
int mp[N][N];
bool visited[N];
int dis[N];
int prim(int &n)
{
memset(visited, false, sizeof(visited));
for(int i=1; i<=n; ++ i)
dis[i] = INF;
dis[1] = 0;
int res = 0;
while(true)
{
int v = -1;
for(int i=1; i<=n; ++ i)
{
if(visited[i] == false && (v == -1 || dis[i] < dis[v]))
v = i;
}
if(v == -1)
break;
if(dis[v] == INF)
return -1;
visited[v] = true, res += dis[v];
for(int i=1; i<=n; ++ i)
dis[i] = min(dis[i], mp[v][i]);
}
return res;
}
void solve(int cases)
{
memset(mp, 0x3f, sizeof(mp));
int n;
scanf("%d", &n);
int sum = 0;
for(int i=1; i<=n; ++ i)
for(int j=1; j<=n; ++ j)
{
scanf("%d", &mp[i][j]);
sum += mp[i][j];
if(mp[i][j] == 0)
mp[i][j] = INF;
mp[i][j] = mp[j][i] = min(mp[i][j], mp[j][i]);
}
int res = prim(n);
if(res == -1)
printf("Case %d: %d\n", cases, -1);
else
printf("Case %d: %d\n", cases, sum - res);
}
int main()
{
int t;
scanf("%d", &t);
for(int i=1; i<=t; ++ i)
solve(i);
return 0;
}