按1的个数排序,一直过不了,求解

输入样例:
3
10011111
00001101
1010101
输出样例:
00001101
1010101
10011111
我的代码:

#include <fstream>
#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;
    int n;
    cin>>n;
    if(n>=1&&n<=100)
    for(int i=1;i<=n;i++){
//while(cin>>str){
cin>>str;
vstr.push_back(str);
//if (cin.get()=='\n')
//break;
}
sort(vstr.begin(),vstr.end(),MyComp);

for(vector<string>::iterator it=vstr.begin();it<vstr.end();it++)
cout<<*it<<endl;
system("pause");
return 0;
}

阅读 1.4k
1 个回答

我刚才测试了下,代码没啥问题,不过题目得再仔细阅读下。

测试数据有多组,这是关键,测试数据有多组,每组的输入都是如下格式。因此代码要改成处理多组数据。

这是我刚提交的代码,你测试下:

#include <iostream>  
#include <string>  
#include <vector>  
#include <algorithm>  
  
using namespace std;  
  
bool MyComp(const string &s1, const string &s2)  
{  
    long c1 = count(s1.begin(), s1.end(), '1');  
    long c2 = count(s2.begin(), s2.end(), '1');  
    return c1 != c2 ? c1 < c2 : s1 < s2;  
}  
  
int main()  
{  
    vector<string> vstr;  
    string str;  
    int n;  
  
    while (cin >> n)  
    {  
        vstr.clear();  
        while (n--)  
        {  
            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;  
}

====

这是哪个oj平台上的题目,可否提供下oj地址?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题