zjut 1044 按1的个数排序
按1的个数排序 Time Limit:1000MS Memory Limit:32768K
Description:
有一些01字串,将其按1的个数的多少的顺序进行输出。
Sample Input:
10011111 00001101 1010101 1 0 1100
Sample Output:
0 1 1100 00001101 1010101 10011111
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[10000][256];
int cmp ( const void *a , const void *b )
{ char *x=(char *)a,*y=(char *)b;
int i=0,j=0,k;
k=0;
while(x[k]) {if(x[k]=='1') i++; k++;}
k=0;
while(y[k]) {if(y[k]=='1') j++; k++;}
//if ( strlen(x)!=strlen(y) ) return strlen(x)-strlen(y);
if (i!=j) return i-j;
return strcmp(x,y);
}
int main(int argc, char *argv[])
{ int i,n;
n=0;
while ( scanf("%s",s[n])!=EOF ) n++;
qsort(s,n,sizeof(s[0]),cmp);
for (i=0; i<n; i++)
printf("%s\n",s[i]);
return 0;
}
**************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[10000][256];
int one(char *x)
{ int c=0,i=0;
while (x[i]!='\0')
{ if (x[i]=='1') c++;
i++;
}
return c;
}
int cmp ( const void *a , const void *b )
{ char *x=(char *)a,*y=(char *)b;
int i=one(x),j=one(y),k;
if (i!=j) return i-j;
return strcmp(x,y);
}
int main(int argc, char *argv[])
{ int i,n;
n=0;
while ( scanf("%s",s[n])!=EOF ) n++;
qsort(s,n,sizeof(s[0]),cmp);
for (i=0; i<n; i++)
printf("%s\n",s[i]);
return 0;
}
*************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[10000][256];
int one(char *x)
{ int c=0,i=0;
while (x[i]!='\0')
{ if (x[i]=='1') c++;
i++;
}
return c;
}
int cmp ( const void *a , const void *b )
{ char *x=(char *)a,*y=(char *)b;
int i=one(x),j=one(y),k;
//if ( strlen(x)==strlen(y) )
if (i==j) return strcmp(x,y);
else return i-j;
// else return strlen(x)-strlen(y);
}
int main(int argc, char *argv[])
{ int i,n;
n=0;
while ( scanf("%s",s[n])!=EOF ) n++;
qsort(s,n,sizeof(s[0]),cmp);
for (i=0; i<n; i++)
printf("%s\n",s[i]);
return 0;
}
#include<iostream> #include<cstring> #include<string> #include<algorithm> using namespace std; int f(string a) { int i,sum=0; for(i=0;a[i];i++) if(a[i]=='1') sum++; return sum; } bool cmp(string a,string b) { if(a.size()!=b.size()) return a.size()<b.size(); else { if(f(a)<f(b)) return 1; if(f(a)==f(b)) { if(a<b) return 1; } } return 0; } int main() { string a[1000]; int i=0,j; while(cin>>a[i]) i++; sort(a,a+i,cmp); for(j=0;j<i;j++) cout<<a[j]<<endl; return 0; } ********************** #include <cstdio> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; bool MyComp(const string &s1,const string &s2) { int c1=count(s1.begin(),s1.end(),'1'); int c2=count(s2.begin(),s2.end(),'1'); return c1!=c2?c1<c2:s1<s2; } int main() { vector<string>vstr; string str; while(cin>>str) { vstr.push_back(str); } sort(vstr.begin(),vstr.end(),MyComp); for(vector<string>::iterator it=vstr.begin();it<vstr.end();it++) { cout<<*it<<endl; } return 0; }