poj2377

最大生成树,注意边数组开二倍大小。注意不连通输出-1;

View Code
   
     
#include < iostream >
#include
< cstdio >
#include
< cstdlib >
#include
< cstring >
#include
< queue >
using namespace std;

#define maxn 1005
#define maxm 20005

struct Edge
{
int v, next, w;
Edge(
int vv, int nn, int ww) :
v(vv), next(nn), w(ww)
{
}
Edge()
{
}
} edge[maxm
* 2 ];

int head[maxn], count;
bool vis[maxn];
int ans = 0 ;
int m, n;

bool operator < ( const Edge & a, const Edge & b)
{
return a.w < b.w;
}

void addedge( int u, int v, int w)
{
edge[count].next
= head[u];
edge[count].v
= v;
edge[count].w
= w;
head[u]
= count;
count
++ ;
}

void input()
{
scanf(
" %d%d " , & n, & m);
for ( int i = 0 ; i < m; i ++ )
{
int a, b, c;
scanf(
" %d%d%d " , & a, & b, & c);
a
-- , b -- ;
addedge(a, b, c);
addedge(b, a, c);
}
}

void prim( int src)
{
priority_queue
< Edge > pq;
int pre = 0 ;
Edge temp;
pq.push(Edge(src,
0 , 0 ));
while ( ! pq.empty())
{
do
{
temp
= pq.top();
pq.pop();
}
while ( ! pq.empty() && vis[temp.v]);
if (vis[temp.v])
return ;
vis[temp.v]
= true ;
pre
= temp.v;
ans
+= temp.w;
for ( int i = head[pre]; i != - 1 ; i = edge[i].next)
if ( ! vis[edge[i].v])
pq.push(edge[i]);
}
}

int main()
{
// freopen("t.txt", "r", stdin);
memset(head, - 1 , sizeof (head));
memset(vis,
0 , sizeof (vis));
count
= 0 ;
input();
prim(
0 );
bool ok = true ;
for ( int i = 0 ; i < n; i ++ )
if ( ! vis[i])
{
ok
= false ;
break ;
}
if (ok)
printf(
" %d\n " , ans);
else
printf(
" %d\n " , - 1 );
return 0 ;
}

你可能感兴趣的:(poj)