Training 6 - G题
输入
每个测试点(输入文件)有且仅有一组测试数据。
在一组测试数据中:
第1行为1个整数N,表示小Hi拥有的城市数量。
接下来的N行,为一个N*N的矩阵A,描述任意两座城市之间建造道路所需要的费用,其中第i行第j个数为Aij,表示第i座城市和第j座城市之间建造道路所需要的费用。
对于100%的数据,满足N<=10^3,对于任意i,满足Aii=0,对于任意i, j满足Aij=Aji, 0<Aij<10^4.
输出
对于每组测试数据,输出1个整数Ans,表示为了使任意两座城市都可以通过所建造的道路互相到达至少需要的建造费用。
Sample Input
5
0 1005 6963 392 1182
1005 0 1599 4213 1451
6963 1599 0 9780 2789
392 4213 9780 0 5236
1182 1451 2789 5236 0
Sample Output
4178
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e7 + 5;
const int maxn = 1e3 + 5;
int a[maxn][maxn], d[maxn];
int n;
ll ans;
bool v[maxn];
void prim()
{
memset(d, 0x3f, sizeof(d));
memset(v, 0, sizeof(v));
d[1] = 0;
for (int i = 1; i < n; i++)
{
int x = 0;
for (int j = 1; j <= n; j++)
if (!v[j] && (x == 0 || d[j] < d[x]))
x = j;
v[x] = 1;
for (int y = 1; y <= n; y++)
if (!v[y])
d[y] = min(d[y], a[x][y]);
}
}
int main()
{
scanf("%d", &n);
memset(a, 0x3f, sizeof(a));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &a[i][j]);
prim();
for (int i = 2; i <= n; i++)
ans += d[i];
printf("%d\n", ans);
return 0;
}
思路:
Prim求最小生成树模板。