题目链接:http://acm.zzuli.edu.cn/showproblem?problem_id=1245

近几天开始复习算法,今天就拿出并查集复习,虽然思想是有的,但是具体细节实现的时候还是出现了失误,其实“塞翁失马,安知非福”,作为一种鞭策吧。


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int T,m,n,s,t,v;
int flag[1000];
struct node
{
int s,t,v;
}count[1000]; ////第一次开数组开的太小了,结果Runtime Error了

int cmp(const void *a,const void *b)
{
struct node *c = (struct node *)a;
struct node *d = (struct node *)b;
if(c->v != d->v)
return c->v - d->v;
else
return c->s - d->s;
}

int find(int x)
{
if(flag[x]!=x)
return flag[x]=find(flag[x]); ////这个递归算法曾面试中出现过,有必要记住
return x;
}
void Merge(int x,int y)
{
int i = find(x);
int j = find(y);
if(i>j)
flag[j]=i; ////这点还是注意的,还是很好好理解的
else
flag[i]=j;
}

int main()
{
int i,k1,k2,sum;
scanf("%d",&T);
while(T--)
{
sum=0;
memset(count,0,sizeof(count));
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d%d%d",&count[i].s,&count[i].t,&count[i].v);
}
qsort(count,m,sizeof(count[0]),cmp);
for(i=0;i<=n;i++)
flag[i]=i;
for(i=0;i<m;i++)
{
k1=find(count[i].s);
k2=find(count[i].t);
if(k1!=k2)
{
sum+=count[i].v;
Merge(count[i].s,count[i].t);
}
}
printf("%d\n",sum);
}
return 0;
}

 

View Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int T,m,n,s,t,v;
int flag[1000];
struct node
{
int s,t,v;
}count[1000000]; ////第一次开数组开的太小了,结果Runtime Error了

int cmp(const void *a,const void *b)
{
struct node *c = (struct node *)a;
struct node *d = (struct node *)b;
if(c->v != d->v)
return c->v - d->v;
else
return c->s - d->s;
}

int find(int x)
{
if(flag[x]!=x)
return flag[x]=find(flag[x]); ////这个递归算法曾面试中出现过,有必要记住
return x;
}
void Merge(int x,int y)
{
int i = find(x);
int j = find(y);
if(i>j)
flag[j]=i; ////这点还是注意的,还是很好好理解的
else
flag[i]=j;
}

int main()
{
int i,k1,k2,sum;
scanf("%d",&T);
while(T--)
{
sum=0;
memset(count,0,sizeof(count));
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d%d%d",&count[i].s,&count[i].t,&count[i].v);
}
qsort(count,m,sizeof(count[0]),cmp);
for(i=0;i<=n;i++)
flag[i]=i;
for(i=0;i<m;i++)
{
k1=find(count[i].s);
k2=find(count[i].t);
if(k1!=k2)
{
sum+=count[i].v;
Merge(count[i].s,count[i].t);
}
}
printf("%d\n",sum);
}
return 0;
}



posted on 2012-03-04 19:35  world_ding  阅读(213)  评论(0编辑  收藏  举报