HDU 3371的弱化版,怎么都能过。
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
const int MAXN = 1e2 + 3;
const int INF = 1e9;
int N, Q;
int g[MAXN][MAXN];
int d[MAXN];
bool vis[MAXN];
int ans;
void init()
{
//fill(g[0], g[0] + MAXN*MAXN, INF); // 没必要了,都直接邻接矩阵输入了
fill(d + 1, d + N + 1, INF);
fill(vis + 1, vis + N + 1, false);
ans = 0;
}
int prim(int s)
{
d[s] = 0;
for (int i = 0; i < N; i++)
{
int mind = INF, u = -1;
for (int j = 1; j <= N; j++)
{
if (!vis[j] && d[j] < mind)
{
mind = d[j];
u = j;
}
}
vis[u] = true;
ans += mind;
for (int j = 1; j <= N; j++)
{
if (!vis[j] && g[u][j] != INF) // 这个!=INF的判断其实也没必要了
{
if (g[u][j] < d[j])
d[j] = g[u][j];
}
}
}
return ans;
}
int main()
{
int a, b;
for (; ~scanf("%d", &N);)
{
init();
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
scanf("%d", &a);
/*if (i != j)*/ g[i][j] = a; // 这个判断不用加,因为prim算法里有!vis[j]限制着,自己不可能再访问自己
}
}
scanf("%d", &Q);
for (int i = 0; i < Q; i++) // n(n+1)/2 其实就是 n(n-1)/2 + n
{
scanf("%d%d", &a, &b);
g[a][b] = g[b][a] = 0; //
}
printf("%d\n", prim(1));
}
return 0;
}