| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
Prim水过~#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#define Inf 0x3f3f3f3f
#define _clr memset(x,0,sizeof(x))
using namespace std;
inline int min(int a, int b) { return a < b ? a : b;}
inline int max(int a, int b) { return a > b ? a : b;}
inline void swap(int &a, int &b) { int temp = a; a = b; b = temp;}
const int MAXN = 110;
int edge[MAXN][MAXN]; //邻接矩阵
int d[MAXN];
bool vis[MAXN];
int p[110];
int n, m, k;
int Prim(int s)
{
memset(vis, false, sizeof(vis));
for(int i = 1; i <= n; ++i) d[i] = Inf;
d[s] = 0;
int res = 0;
for(int i = 1; i <= n; ++i)
{
int u = -1;
for(int j = 1; j <= n; ++j)
{
if(!vis[j] && (u == -1 || d[j] < d[u]))
{
u = j;
}
}
if(u == -1 || d[u] == Inf) return -1; //判断不连通的情况
vis[u] = true;
res += d[u];
for(int v = 1; v <= n; ++v)
{
if(!vis[v] && edge[u][v] < d[v])
{
d[v] = edge[u][v];
}
}
}
return res;
}
int main()
{
//freopen("aa.in", "r", stdin);
int i, j, u, v, w, Q;
scanf("%d", &n);
for(i = 1; i <= n; ++i)
{
for(j = 1; j <= n; ++j)
{
scanf("%d", &w);
edge[i][j] = w;
}
}
scanf("%d", &Q);
while(Q--)
{
scanf("%d %d", &u, &v);
edge[u][v] = edge[v][u] = 0;
}
printf("%d\n", Prim(1));
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator