题目链接:UVa 10420 - List of Conquests
排序问题,题目本身不难,注意一些东西。
sort的cmp返回值只有两个,0或者1,分别表示小于和大于。
qsort的返回值有三个,-1或者0或者1,分别表示小于,等于,大于,稳定的。
所以在sort的cmp中写 return strcmp(_a, _b);肯定是错的,因为strcmp的返回值有三个,用qsort是可以的。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stdio.h>
using namespace std;
struct country
{
char name[80];
int num = 0;
};
int T;
char name_women[80];
char name_country[80];
country c[2000 + 5];
int cmp(const void *_a,const void *_b)
{
country *a = (country *)_a;
country *b=(country *)_b;
return strcmp(a->name,b->name);
}
int main()
{
cin>>T;
int n = 0;
bool flag = false;
while(T--)
{
flag = false;
cin>>name_country;
gets(name_women);
for(int i = 0;i < n;i++)
{
if(!strcmp(c[i].name,name_country))
{
c[i].num++;
flag = true;
break;
}
}
if(!flag)
{
strcpy(c[n].name,name_country);
c[n++].num++;
}
}
qsort(c,n,sizeof(c[0]),cmp);
for(int i = 0;i < n;i++)
cout<<c[i].name<<" "<<c[i].num<<endl;
return 0;
}
本文详细介绍了如何解决UVa10420题目的排序问题,包括cmp与qsort的区别使用,以及代码实现的优化。
171

被折叠的 条评论
为什么被折叠?



