关于sort中的cmp函数 (玄关)
  • 板块灌水区
  • 楼主hayoon
  • 当前回复19
  • 已保存回复19
  • 发布时间2024/8/24 22:00
  • 上次更新2024/8/25 09:58:43
查看原帖
关于sort中的cmp函数 (玄关)
915383
hayoon楼主2024/8/24 22:00

再今天晚上的abcB题中,有一个蒟蒻写了这样一份代码:

#include<bits/stdc++.h>
using namespace std;
int a[20100];
bool cmp(int x,int y)
{
	if(x<y)
	return 0;
	else
	return 1;
}
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	scanf("%d",&a[i]);
	sort(a+1,a+n+1,cmp);
	int ans=0; 
	while(a[2]>0)
	{
		a[1]--;
		a[2]--;
		sort(a+1,a+n+1,cmp);
		ans++;
	}
	printf("%d",ans);
	return 0;
}

然后发现Wa了 然后他把代码改成了这样:

#include<bits/stdc++.h>
using namespace std;
int a[20100];
bool cmp(int x,int y)
{
	if(x>y)
	return 1;
	else
	return 0;
}
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	scanf("%d",&a[i]);
	sort(a+1,a+n+1,cmp);
	int ans=0; 
	while(a[2]>0)
	{
		a[1]--;
		a[2]--;
		sort(a+1,a+n+1,cmp);
		ans++;
	}
	printf("%d",ans);
	return 0;
}

然后就过了,可见两份代码的不同之处只有cmp函数内的内容。
所以,这个蒟蒻想问一下大佬们cmpcmp函数再sortsort中的含义是什么,是返回1那么不进行交换操作,返回0则进行交换操作吗

2024/8/24 22:00
加载中...