警示后人
查看原帖
警示后人
713865
zhu_yu_yang楼主2024/2/23 15:03

并查集+背包!!!

首先荣获64分的

满分

#include<bits/stdc++.h>
using  namespace std;
int f[20010],n,m,k,x,y,fs[20010],ans,mn=INT_MAX;
bool b[20010];
int father(int x)
{
	if(f[x]!=x)
		f[x]=father(f[x]);
	return f[x];
}
int main()
{
	cin>>n>>m>>k;
	for(int i=1;i<=n;++i)
		f[i]=i,fs[i]=1;
	for(int i=1;i<=k;++i)
	{
		cin>>x>>y;
		int fx=father(x);
		int fy=father(y);
		if(fx!=fy)
		{
			f[fx]=fy;
			fs[fy]+=fs[fx];
		}
			
	}
	b[0]=1;
	//for(int i=1;i<=n;++i)
	//	cout<<fs[father(i)]<<'\n';
	for(int i=1;i<=n;++i)
		for(int j=n;j>=fs[father(i)];--j)
			if(b[j-fs[father(i)]])
				b[j]=1;
	
	for(int i=1;i<=n;++i)
	{
		//cout<<b[i]<<'\n';
		//if(b[i])
		//	cout<<i<<'\n';
		if(b[i] && abs(m-i)<mn)
			mn=abs(m-i),ans=i;
	}
	cout<<ans;
}

终于经过无数次的**尝试

给出以下几个可能的错误

1.T1 可能会超时 见下文32行优化

2.上文第36行 i 从 0 开始!!

上代码!!!

#include<bits/stdc++.h>
using  namespace std;
int f[20010],n,m,k,x,y,fs[20010],ans,mn=INT_MAX;
bool b[20010];
int father(int x)
{
	if(f[x]!=x)
		f[x]=father(f[x]);
	return f[x];
}
int main()
{
	cin>>n>>m>>k;
	for(int i=1;i<=n;++i)
		f[i]=i,fs[i]=1;
	for(int i=1;i<=k;++i)
	{
		cin>>x>>y;
		int fx=father(x);
		int fy=father(y);
		if(fx!=fy)
		{
			f[fx]=fy;
			fs[fy]+=fs[fx];
		}
			
	}
	b[0]=1;
	//for(int i=1;i<=n;++i)
	//	cout<<fs[father(i)]<<'\n';
	for(int i=1;i<=n;++i)
		if(f[i]==i)
			for(int j=n;j>=fs[i];--j)
				if(b[j-fs[i]])
					b[j]=1;
	
	for(int i=0;i<=n;++i)
		if(b[i] && abs(m-i)<mn)
			mn=abs(m-i),ans=i;

	cout<<ans;
}

2024/2/23 15:03
加载中...