64-题目1190:大整数排序

65 篇文章 0 订阅
12 篇文章 0 订阅

http://ac.jobdu.com/problem.php?pid=1190

在本地是运行正确的,但是提交时总是wrong answer!

#include<iostream>
#include<algorithm>
#include<fstream>
#include<string.h>
using namespace std;

struct Number
{
	char str[1000];
	int len;
};
bool cmp1(Number a, Number b)   //按长度递增排序
{
	return a.len < b.len;
}
bool cmp2(Number a, Number b)    //按数字序列大小排序,前提是长度相等
{
	int i= strcmp(a.str, b.str);   //若str1 == str2,则返回零;若str1>str2,则返回正数;若str1<str2,则返回负数。
	if (i < 0)
		return true;
	else
		return false;
	    
}
int main()
{
	int N, i, j;
	//ifstream cin("data.txt");
	while (cin >> N)
	{
		getchar();   //把N后面的换行读取
		Number *num = new Number[N];
		for (i = 0; i < N; i++)    //输入数据
		{
			j = 0;
			while (scanf_s("%c", &num[i].str[j]) && num[i].str[j] != '\n') j++;   //只能用scanf判断换行
			num[i].len = j;
		}  

		sort(num, num + N, cmp1);   //按长度递增排序
		for (i = 0; i < N; i++)
		{
			j = i;
			while (j < N - 1  && num[j].len == num[j + 1].len) j++;
			if (i != j)
				sort(num+i, num+j+1, cmp2);  // 对长度相同的数组进行大小排序
			i = j;
		}

		for (i = 0; i < N; i++)
		{
			for (j = 0; j < num[i].len; j++)
				cout << num[i].str[j];
			cout << endl;
		}

	}//end of while
	system("pause");
	return 0;
}
我找到一个AC代码,思路和我的一样,但是更加简洁,用的vector

不需要比较两次,我是先比较长度,长度相同的比较大小,而且我用string会出现 “没有与这些操作上匹配的“>>”运算符 操作数类型为std::istream>>num ” 的问题,不管头文件是<string>还是<string.h>,我发现这个真是不能理解编译器。。。。。

别人是用string,而且在一个cmp里比较完毕!

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

bool cmp(string a, string b)//自定义排序准则 
{
	if (a.size() != b.size())
		return a.size() < b.size();
	return a < b;
}
int main()
{
	int n;
	while (cin >> n)
	{
		int i;
		vector<string> coll(n);//定义一个大小为n的字符串数组 
		for (i = 0; i < n; i++)
			cin >> coll[i];
		sort(coll.begin(), coll.end(), cmp);//前两个为迭代器,最后一个是排序准则;标准库中排序函数 
		for (i = 0; i < n; i++)
			cout << coll[i] << endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值