为什么我的贪心不行?
查看原帖
为什么我的贪心不行?
1152799
wsy_I楼主2024/6/28 20:14

我之前看到了很多人说不要用贪心,但是我发现了一种他们举的反例都能过的贪心。(但还是不对,全WA)

话不多说请大佬dalao看看我的代码:

#include<bits/stdc++.h>
using namespace std;
int s1,s2,s3,s4,A[25],B[25],C[25],D[25],ans=0;
bool cmp(int a1,int b1)
{
	return a1>b1; 
}
int main()
{
	scanf("%d%d%d%d",&s1,&s2,&s3,&s4);
	for(int i=1;i<=s1;i++) scanf("%d",&A[i]);
	sort(A+1,A+s1+1,cmp);
	int Z=1,Y=1;
	while(Z<=s1&&Y<=s1){
		if(A[Z]>A[Y]){
			A[Z]-=A[Y];
			Y=max(Y,Z)+1;
			ans+=A[Y];
			A[Y]=0;
		}
		else if(A[Z]<A[Y]){
			A[Y]-=A[Z];
			Z=max(Y,Z)+1;
			ans+=A[Z];
			A[Z]=0;
		}
		else{
			ans+=A[Y];
			A[Y]=0;
			A[Z]=0;
			Y=max(Y,Z)+1;
			Z=Y+1;
		}
	}
	if(A[s1-2]!=0) ans+=A[s1-2];
	else ans+=A[s1-1];
	ans+=A[s1];
	for(int i=1;i<=s2;i++) scanf("%d",&B[i]);
	sort(B+1,B+s2+1,cmp);
	Z=1;Y=1;
	while(Z<=s2&&Y<=s2){
		if(B[Z]>B[Y]){
			B[Z]-=B[Y];
			Y=max(Y,Z)+1;
			ans+=B[Y];
			B[Y]=0;
		}
		else if(B[Z]<B[Y]){
			B[Y]-=B[Z];
			Z=max(Y,Z)+1;
			ans+=B[Z];
			B[Z]=0;
		}
		else{
			ans+=B[Y];
			B[Y]=0;
			B[Z]=0;
			Y=max(Y,Z)+1;
			Z=Y+1;
		}
	}
	if(A[s2-2]!=0) ans+=B[s2-2];
	else ans+=B[s2-1];
	ans+=B[s2];
	for(int i=1;i<=s3;i++) scanf("%d",&C[i]);
	Z=1;Y=1; 
	sort(C+1,C+s1+1,cmp);
	while(Z<=s3&&Y<=s3){
		if(C[Z]>C[Y]){
			C[Z]-=C[Y];
			Y=max(Y,Z)+1;
			ans+=C[Y];
			C[Y]=0;
		}
		else if(C[Z]<C[Y]){
			C[Y]-=C[Z];
			Z=max(Y,Z)+1;
			ans+=C[Z];
			C[Z]=0;
		}
		else{
			ans+=C[Y];
			C[Y]=0;
			C[Z]=0;
			Y=max(Y,Z)+1;
			Z=Y+1;
		}
	}
	if(C[s3-2]!=0) ans+=C[s3-2];
	else ans+=C[s3-1];
	ans+=C[s1];
	for(int i=1;i<=s4;i++) scanf("%d",&D[i]);
	sort(D+1,D+s1+1,cmp);
	Z=1;Y=1;
	while(Z<=s4&&Y<=s4){
		if(D[Z]>D[Y]){
			D[Z]-=D[Y];
			Y=max(Y,Z)+1;
			ans+=D[Y];
			D[Y]=0;
		}
		else if(D[Z]<D[Y]){
			D[Y]-=D[Z];
			Z=max(Y,Z)+1;
			ans+=D[Z];
			D[Z]=0;
		}
		else{
			ans+=D[Y];
			D[Y]=0;
			D[Z]=0;
			Y=max(Y,Z)+1;
			Z=Y+1;
		}
	}
	if(D[s4-2]!=0) ans+=A[s4-2];
	else ans+=A[s4-1];
	ans+=A[s4];
	cout<<ans;
	return 0;
}

写的又长又臭。。。大家帮帮我吧!

2024/6/28 20:14
加载中...