ACM Simple Sort 的个人解法

题目描述

Give some strings that consist of “0” and “1”, you sort them by the number of “1” in the string, and if they have the same number , then sort by the position of the “1” appears, the more lately ‘1’ appears, the string is the more “bigger” of . such as the string “00110” should stand behind the string “11000”, “111001” should stand behind the string “111010”. The output should remain they original order to those strings that has no ‘1’ at all.

输入

The first line N is the number of strings(N<=100). The next N lines is the strings to be sort. ( the length of each string is less than 100 )

输出

The sorted strings

样例输入

8
000
000111000
1100001
101100001
0000000
000110001
101110
00000

样例输出

000
0000000
00000
1100001
000111000
000110001
101110
101100001

我的解法:

#include <iostream>

using namespace std;
#define     MAX     100
int n = 0, k = 0;

/*judge if the string contains '1'*/
bool hasOne(string str)
{
	int len = str.size();

	for (int i = 0; i < len; i++)
	{
		if (str[i] == '1')
		{
			return true;
		}
	}
	return false;
}

/*the count of '1'*/
int countOfOne(string str)
{
	int cou = 0;
	for (int i = 0; i < str.size(); i++)
	{
		if (str[i] == '1')
		{
			cou++;
		}
	}
	return cou;
}

int cmpPos(string src, string dest)
{
	int len = src.size() <= dest.size() ? src.size() : dest.size();
	int i = 0;
	
	for (i = 0; i < len; i++)
	{
		if (src[i] == '1')
		{
			if (dest[i] != '1')
			{					// src < dest
				return -1;
			}
			else
			{
				continue;
			}
		}
		else
		{
			if (dest[i] == '1')
			{					// src > dest
				return 1;
			}else {
				continue;
			}
		}
	}
	// src == dest
	return 0;

}

/*compare two strings*/
int strCmp(string src, string dest){
if (countOfOne(src) < countOfOne(dest)){ // src < dest
return -1;
}else if (countOfOne(src) > countOfOne(dest)){ // src > dest
return 1;
}else{ // the count of character '1' in src and dest is equal
return cmpPos(src, dest);
}
}

 
/*bubble sort*/
void strSort(string strs[])
{
	for (int i = 0; i < k - 1; i++)
	{
		for (int j = 0; j < k -1; j++)
		{			
			if (strCmp(strs[j], strs[j + 1]) == 1)
			{					// strs[j] > strs[j+1]
				string temp = strs[j];
				strs[j] = strs[j + 1];
				strs[j + 1] = temp;
			}
		}
	}
}


int main()
{

	string src[MAX], dest[MAX], temp[MAX];

	cin >> n;
	int j = 0;
	for (int i = 0; i < n; i++)
	{
		cin >> temp[i];
		if (!hasOne(temp[i]))
		{
			dest[j++] = temp[i];
		}
		else
		{
			src[k++] = temp[i];
		}
	}
	
	 strSort(src);

	for (int i = 0; i < n; i++)
	{
		dest[j++] = src[i];
	}
	for (int i = 0; i < n; i++)
	{
		cout << dest[i] << endl;
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值