01串排序

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

只是用for循环,问题在str[n].size()长度的读取不准

#include
#include
#include
#include
using namespace std;
int main()
{
	string str[100];
	int i = 0, a[257] = { 0 };
	while (cin >> str[i++]);//最终一共有i串,最后一个串应该是i-1个
	//长度
	for (int n = 0; n < i-1; n++)//输入ctrl+z作为结束的时候,有可能进行了i++;
	{
		int min= n;
		a[str[n].size()]++;//记录每个串的长度
		cout << str[n].size() << endl;
		for (int m = n + 1; m < i; m++)
		{
			if (str[m].size() < str[min].size())min = m;
		}
		if (min != n)
		{
			string t=str[min];
			str[min] = str[n];
			str[n] = t;
		}
	}
	cout << "长度为7和8的个数" << endl;
	cout << a[7] << endl << a[8] << endl;
	//1的个数
	int b[100] = { 0 },all=0;//数组b记录1的个数
	for (int n = 1; n <= 256; n++)
	{//循环开始时all表示的是相同长度字符串的第一个
		memset(b, 0, sizeof(b));
		if (a[n] >= 2)//对应长度有两个以上字符串
		{
			//记录1的个数
			for (int m = 1; m <= a[n]; m++)
			{
				for (int l = 0; str[all + m - 1][l] != '\0'; l++)
					if (str[all + m - 1][l] == '1')b[all+m-1]++;
			}
			for (int m = all; m < all + a[n]; m++)//m和l都是字符串数组中的位置
			{
				int min = m;
				for (int l = m + 1; l < all + a[n]; l++)
					if (b[l] < b[min])min = l;
				if (min != m)
				{
					string t=str[min];
					str[min] = str[m];
					str[m] = t;
				}
			}
			//ascii
			for (int m = all; m < all + a[n]; m++)//m和l都是字符串数组中的位置
			{
				int min = m;
				for (int l = m + 1; l < all + a[n]; l++)
					if (b[l] == b[min])continue;
					else if (str[l]<str[min])min = l;
				if (min != m)
				{
					string t = str[min];
					str[min] = str[m];
					str[m] = t;
				}
			}
		 }
		all += a[n];
	}
	//ascii排序
	for (int n = 0; n < i; n++)
		cout << str[n] << endl;
}

多重比较的时候,一个bool函数按顺序比较(但是平台还是没有通过)

#include
#include
#include
using namespace std;
bool prime(string a, string b)//前面是小的
{
	if (a.size() > b.size())return false;//比较长度
	int a1 = count(a.begin(), a.end(), '1');//count函数记录字符串字符1的个数
	int b1 = count(b.begin(), b.end(), '1');
	if (a1 > b1)return false;//1的个数比较
	if (a > b)return false;//ascii值比较
	return true;
}
int main()
{
	string str[10];
	int all = 0;
	while (cin >> str[all++]);
	for (int i = 0; i < all; i++)
	{
		int min = i;
		for (int j = i + 1; j < all; j++)
		{
			if (prime(str[min], str[j]))continue;
			else min = j;
		}
		if (min != i)
		{
			string t = str[min]; str[min] = str[i]; str[i] = t;
		}
	}
	for (int i = 0; i < all; i++)
		cout << str[i] << endl;
}
//0 1 100 101 110 111

在这里插入图片描述

你可能感兴趣的:(竞赛)