Description:
将01串首先按长度排序,长度相同时,按1的个数多少进行排序,1的个数相同时再按ASCII码值排序。
Input:
输入数据中含有一些01串,01串的长度不大于256个字符。
OutPut:
重新排列01串的顺序。使得串按基本描述的方式排序。
Sample Input:
10011111 00001101 1010101 1 0 1100
Sample Output:
0 1 1100 1010101 00001101 10011111心得:学会巧妙应用三目操作符,简化代码。
STL中习题不要用手写的循环。比如如果仅是输出操作可以用copy算法输出,一行代码就可以搞定。
代码如下:
#include<iostream>
#include<fstream>
#include<set>
#include<string>
#include<queue>
#include<set>
#include<iterator>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<numeric>
using namespace std;
struct myCmp
{
bool operator()(const string& str1,const string& str2)
{
//if (str1.length() != str2.length())
//{
// return str1.length() < str2.length();
//}
//else
//{
// int num1 = count(str1.begin(), str1.end(), '1');
// int num2 = count(str2.begin(), str2.end(), '1');
// /*if (num1 != num2)
// {
// return num1 < num2;
// }
// else
// {
// return str1 < str2;
// }*/
// return (num1 != num2 ? num1 < num2 : str1 < str2);
//}
if (str1.length() != str2.length())
{
return str1.length() < str2.length();
}
int num1 = count(str1.begin(), str1.end(), '1');
int num2 = count(str2.begin(), str2.end(), '1');
return (num1 != num2 ? num1 < num2 : str1 < str2);
}
};
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("D:\\in.txt", "r", stdin);
freopen("D:\\out.txt", "w", stdout);
#endif
multiset<string, myCmp> coll;
string str;
while (cin>>str)
{
coll.insert(str);
}
/* multiset<string, myCmp>::iterator it;
for (it = coll.begin(); it != coll.end(); it++)
{
cout << *it << endl;
}*/
ostream_iterator<string> os(cout, "\n");
copy(coll.begin(), coll.end(), os);
return 0;
}
本题还有一种扩展形式,即只按 01 串中 1 的个数的多少进行升序排序。
代码中如果1的个数相同,按出现的先后顺序排序,用
return num1<num2;
如果1的个数相同,要按ASCII码进行排序,则用
return (num1!=num2?num1<num2:str1<str2);
代码如下:
#include<iostream>
#include<fstream>
#include<set>
#include<string>
#include<queue>
#include<set>
#include<iterator>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<numeric>
using namespace std;
struct myCmp
{
bool operator()(const string& str1,const string& str2)
{
int num1 = count(str1.begin(), str1.end(), '1');
int num2 = count(str2.begin(), str2.end(), '1');
//如果1的数量不等,按1的个数排序
//如果1的数量相等,则按出现的先后顺序排序
//只能用“>”或“<”,不能用“=”
// return num1<num2;
//如果1的数量相等,要按ASCII码大小排序
return (num1 != num2 ? num1 < num2 : str1 < str2);
}
};
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("D:\\in.txt", "r", stdin);
freopen("D:\\out.txt", "w", stdout);
#endif
vector<string> coll;
string str;
while (cin>>str)
{
coll.push_back(str);
}
sort(coll.begin(), coll.end(), myCmp());
copy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));
return 0;
}