就是赤裸裸的最小生成树啊~
PRIM算法:
Executing... Test 1: TEST OK [0.003 secs, 3404 KB] Test 2: TEST OK [0.003 secs, 3404 KB] Test 3: TEST OK [0.003 secs, 3404 KB] Test 4: TEST OK [0.003 secs, 3404 KB] Test 5: TEST OK [0.003 secs, 3404 KB] Test 6: TEST OK [0.003 secs, 3404 KB] Test 7: TEST OK [0.003 secs, 3404 KB] Test 8: TEST OK [0.003 secs, 3404 KB] Test 9: TEST OK [0.005 secs, 3404 KB] Test 10: TEST OK [0.008 secs, 3404 KB] All tests OK.
/*
TASK:agrinet
LANG:C++
*/
#include <cstdio>
#include <cstring>
bool vis[100]={0};
int n;
int g[100][100];
int t[100], ans = 0;
int main()
{
freopen("agrinet.in", "r", stdin);
freopen("agrinet.out","w",stdout);
scanf("%d", &n);
memset(t,127,sizeof(t));
for (int i = 0; i != n; ++ i)
for (int j = 0; j != n; ++ j) scanf("%d", &g[i][j]);
t[0] = 0;
for (int i = 0; i != n; ++ i)
{
int now, dis = 0x7ffffff;
for (int j = 0; j != n; ++ j)
if (!vis[j] && t[j] < dis)
{
now = j;
dis = t[j];
}
for (int j = 0; j != n; ++ j)
if (t[j] > g[now][j]) t[j] = g[now][j];
vis[now] = 1;//进入最小生成树
ans += dis;
}
printf("%d\n", ans);
return 0;
}
kur算法……居然比没有堆优化的prim慢,看来稠密图还是prim快
Executing... Test 1: TEST OK [0.008 secs, 3488 KB] Test 2: TEST OK [0.014 secs, 3488 KB] Test 3: TEST OK [0.008 secs, 3488 KB] Test 4: TEST OK [0.005 secs, 3488 KB] Test 5: TEST OK [0.005 secs, 3488 KB] Test 6: TEST OK [0.005 secs, 3488 KB] Test 7: TEST OK [0.008 secs, 3488 KB] Test 8: TEST OK [0.016 secs, 3488 KB] Test 9: TEST OK [0.030 secs, 3488 KB] Test 10: TEST OK [0.030 secs, 3488 KB] All tests OK.
/*
TASK:agrinet
LANG:C++
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int fa[100],ans = 0;;
struct edge
{
int u, v;
int cost;
edge(){}
}a[10000];
int tail = 0;
bool operator < (edge A, edge B)
{
return A.cost < B.cost;
}
int getfather(int k)
{
if (fa[k] == k) return k;
return fa[k] = getfather(fa[k]);
}
int main()
{
freopen("agrinet.in", "r", stdin);
freopen("agrinet.out","w",stdout);
scanf("%d", &n);
for (int i = 0; i != n; ++ i)
for (int j = 0; j != n; ++ j)
{
scanf("%d", &a[tail].cost);
if (i == j) continue;
a[tail].u = i;
a[tail ++ ].v = j;
}
for (int i = 0; i != n; ++ i) fa[i] = i;
sort(a, a + tail);
int t = 0;
for (int i = 0; i != tail; ++ i)
{
int A = getfather(a[i].u);
int B = getfather(a[i].v);
if (A == B) continue;
else{
fa[A] = B;
ans += a[i].cost;
++ t;
}
if (t == n) break;
}
printf("%d\n", ans);
return 0;
}