sort代码

凌艺樽  •  3个月前


#include<bits/stdc++.h>
#pragma GCC optimize(3)
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
const int N=1e3+10;
struct char_01{
	int sum_of_1;
	string s1;
}s[N];
int n;
bool cmp(char_01 x,char_01 y)
{
	if(x.s1.size()==y.s1.size())
	{
		if(x.sum_of_1==y.sum_of_1)
		{
			return x.s1<y.s1;
		}
		return x.sum_of_1<y.sum_of_1;
	}
	return x.s1.size()<y.s1.size();
}
int main()
{
	IOS;
	cin>>n;
	for(int i=1;i<=n;++i)
	{
		cin>>s[i].s1;
		for(int j=1;j<=s[i].s1.size();++j)
		{
			if(s[i].s1[j]=='1')
			{
				s[i].sum_of_1++;
			}
		}
	}
	sort(s+1,s+n+1,cmp);
	for(int i=1;i<=n;++i)
	{
		cout<<s[i].s1<<endl;
	}
    return 0;
}

Comments: