01串排序
题目描述
将01串首先按长度排序,长度相同时,按1的个数多少进行排序,1的个数相同时再按 ASCII 码值排序(字典序)。
输入
第一行输入一个整数n(1<= n <=100),表示字符串的个数。
输入数据中含有一些01串,01串的长度不大于256个字符。
输出
重新排列01串的顺序,使得串按基本描述的方式排序,然后依次输出。
样例输入
6
10011111
00001101
1010101
1
0
1100
样例输出
0
1
1100
1010101
00001101
10011111
代码:
#include<bits/stdc++.h>
using namespace std;
int n;
string a[105];
bool rule(string x,string y){
int lx=x.size(),ly=y.size();
inr ox=0,oy=0;
for(int i=0;i<lx;i++) ox+=x[i]-48;
for(int i=0;i<ly;i++) oy+=y[i]-48;
return lx<ly ||
lx==ly && ox<oy ||
lx==ly && ox==oy && x<y;
}
int main(){
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
sort(a,a+n,rule);
for(int i=0;i<n;i++) cout<<a[i]<<endl;
return 0;
}