Agri-Net
原题链接https://vjudge.net/contest/352170#problem/H
题目以二维数组的形式给出每两个地点之间的关系,使用prim直接计算即可,使用Kruskal的话需要先读取数据,存入结构体再进行计算。
Prim:
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
long long map[3005][3005];
long long n;
long long ans;
long long dis[300005];
bool vis[300005];
void prim()
{
ans = 0;
long long i, j;
for (i = 1; i <= n;i++)
{
dis[i] = map[1][i];
vis[i] = false;
}
vis[1] = true;
for (i = 1; i < n;i++)
{
long long minn = INF;
long long p = 1;
for (j = 1; j <= n;j++)
{
if(!vis[j]&&dis[j]<minn)
{
minn = dis[j];
p = j;
}
}
ans += minn;
vis[p] = true;
for (j = 1;j<=n;j++)
{
if(!vis[j]&&dis[j]>map[p][j])
{
dis[j] = map[p][j];
}
}
}
return;
}
int main()
{
while (~scanf("%lld", &n))
{
long long i,j;
for (i = 1; i <= n;i++)
{
for (j = 1; j <= n;j++)
{
scanf("%lld", &map[i][j]);
}
}
prim();
cout << ans << endl;
}
return 0;
}
Kruskal:
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
long long pre[300005];
long long map[3005][3005];
struct node
{
long long u;
long long v;
long long w;
} stu[600005];
struct id
{
long long x;
long long y;
} stuu[30005];
long long zz;
long long ans;
long long cnt;
bool cmp(node x, node y)
{
return x.w < y.w;
}
long long find(long long x)
{
if (x == pre[x])
{
return x;
}
return pre[x] = find(pre[x]);
}
void join(long long x, long long y, double w)
{
long long ss1 = find(x);
long long ss2 = find(y);
if (ss1 != ss2)
{
pre[ss2] = ss1;
ans += w;
cnt--;
}
}
int main()
{
long long n, i, j;
long long sum1;
while (~scanf("%lld", &n))
{
if(n==0)
{
break;
}
ans = 0;
cnt = n;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
scanf("%lld", &map[i][j]);
}
}
/* for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
//double dis = 1.0 * sqrt(1.0 * (stuu[i].x - stuu[j].x) * (stuu[i].x - stuu[j].x) + 1.0 * (stuu[i].y - stuu[j].y) * (stuu[i].y - stuu[j].y));
cout << map[i][j] << " ";
//= dis;
}
cout << endl;
}*/
/* for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%.2lf ", map[i][j]);
}
cout << endl;
}*/
long long nn, s1, s2;
long long k = 0;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
{
continue;
}
stu[k].u = i;
stu[k].v = j;
stu[k].w = map[i][j];
k++;
}
}
sort(stu, stu + k, cmp);
/* for (i = 0; i < k; i++)
{
printf("*%lld %lld %lld\n", stu[i].u, stu[i].v, stu[i].w);
}
for (i = 0; i <= n;i++)
{
cout << pre[i] << endl;
}
cout << endl;*/
for (i = 0; i <= n; i++)
{
pre[i] = i;
}
/*for (i = 0; i < k; i++)
{
printf("%lld %lld %lld\n", stu[i].u, stu[i].v, stu[i].w);
}*/
for (i = 0; i < k; i++)
{
join(stu[i].u, stu[i].v, stu[i].w);
if (cnt == 1)
{
break;
}
}
cout << ans<<endl;
}
return 0;
}