您的位置:首页 > 其它

64-题目1190:大整数排序

2016-03-12 23:34 447 查看

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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: