• 主页
• 问答

# 这道题为什么我用贪心和并查集提交错了？？

a330416020 2010-08-12 10:04:26

3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0

3
5

#include<iostream>
#include<algorithm>
using namespace std;
int set[105],num[105];
int flag;
struct S
{
int a,b,c;
}d[5000];
bool cmp(S i,S j)
{
return i.c<j.c;
}
int find(int a)
{
int r;
r=a;
while(set[r]!=r)
{
r=set[r];
}
return r;
}
{
if(a==b)
{
return ;
}
if(num[a]<=num[b])
{
set[a]=b;
num[b]=num[a]+num[b];
flag=num[b];
}
else
{
set[b]=a;
num[a]=num[a]+num[b];
flag=num[a];
}
}
int main()
{
int n,i;
while(cin>>n)
{
if(n==0) break;
memset(set,0,sizeof(set));
memset(num,0,sizeof(num));
int t;
t=n*(n-1)/2;
for(i=0;i<t;i++)
{
cin>>d[i].a>>d[i].b>>d[i].c;
}
for(i=1;i<=n;i++)
{
set[i]=i;
num[i]=1;
}
sort(d,d+t,cmp);
int sum=0,f=1;
for(i=0;i<t;i++)
{
if(flag>=n){sum=d[i].c+sum; break;}
if(flag>f)
{
sum=d[i].c+sum;
f=flag;
}
}
cout<<sum<<endl;
}
return 0;
}
...全文
65 点赞 收藏 8

8 条回复

Justmeh 2010-08-12

[Quote=引用 2 楼 berryluo 的回复:]
prim里也有贪心的思想吧
[/Quote]

berryluo 2010-08-12
prim里也有贪心的思想吧

``````
#include<iostream>
using namespace std;
int main()
{
int n,i,j,distance[101][101],lock[101],point,a,b;
while(cin>>n&&n)
{
memset(lock,0,sizeof(lock));
int mintree=0,finded=1,min;
lock[1]=1;
for(i=1;i<=n*(n-1)/2;i++)
{
cin>>a>>b;cin>>distance[a][b];
distance[b][a]=distance[a][b];
}
while(finded!=n)
{
min=100000000;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(lock[i]==1&&lock[j]==0)
if(min>distance[i][j])
{
min=distance[i][j];
point=j;
}

mintree+=min;	lock[point]=1;
finded++;
}
cout<<mintree<<endl;
}

return 0;
}
``````

a330416020 2010-08-12

luozhongzhu 2010-08-12

a330416020 2010-08-12

3.2w+