关于这道题目学会了以下几件事:
1:sort函数第三个参数cmp函数可以指定第三个参数,以此来判断排序方式;
2:看清题目,题目的意思是只排序要求排序的国家;
3:偷懒绝对是好事,我就是不想写很多个cmp才去查是不是能用第三个参数指定排序方式
about:cmp
想要指定cmp的第三个参数,可以重载函数调用运算符,然后就可以愉快的编程了。
贴代码,,,
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
enum Enumcomp{GOLD,MEDAL,GOLD_PEOPLE,MEDAL_PEOPLE,NUMBLE};
//在sort数组里下标代表排名方式,1,2,3,4
struct Country{
int gold;
int medal;
int people;
double gold_people;
double medal_people;
int _sort[5];
int number;
};
class cmp
{
private:
Enumcomp comp;
public:
cmp(Enumcomp c):comp(c){};
bool operator ()(struct Country a,struct Country b)
{
switch(comp){
case GOLD:
return a.gold > b.gold;
case MEDAL:
return a.medal > b.medal;
case GOLD_PEOPLE:
return a.gold_people > b.gold_people;
case MEDAL_PEOPLE:
return a.medal_people > b.medal_people;
case NUMBLE:
return a.number < b.number;
}
}
};
int main()
{
int m,n;
while((scanf("%d%d",&n,&m))!=EOF)
{
struct Country country1[n],country[n];
int flag=0;
//输入数据
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&country1[i].gold,&country1[i].medal,&country1[i].people);
country1[i].gold_people=((double)(country1[i].gold))/country1[i].people;
country1[i].medal_people=((double)(country1[i].medal))/country1[i].people;
for(int j=0;j<5;j++)
{
country1[i]._sort[j]=100;
country[i]._sort[j]=100;
}
country1[i].number=i;
}
for(int i=0;i<m;i++)
{
int choice;
scanf("%d",&choice);
country[flag].gold=country1[choice].gold;
country[flag].medal=country1[choice].medal;
country[flag].people=country1[choice].people;
country[flag].gold_people=country1[choice].gold_people;
country[flag].medal_people=country1[choice].medal_people;
country[flag].number=country1[choice].number;
flag++;
}
//gold 排序
sort(country,country+flag,cmp(GOLD));
country[0]._sort[1]=1;
for(int i=1;i<flag;i++)
{
if(country[i].gold==country[i-1].gold)
country[i]._sort[1]=country[i-1]._sort[1];
else
country[i]._sort[1]=i+1;
}
//medal排序
sort(country,country+flag,cmp(MEDAL));
country[0]._sort[2]=1;
for(int i=1;i<flag;i++)
{
if(country[i].medal==country[i-1].medal)
country[i]._sort[2]=country[i-1]._sort[2];
else
country[i]._sort[2]=i+1;
}
//gold_ppeople排序
sort(country,country+flag,cmp(GOLD_PEOPLE));
country[0]._sort[3]=1;
for(int i=1;i<flag;i++)
{
if(country[i].gold_people==country[i-1].gold_people)
country[i]._sort[3]=country[i-1]._sort[3];
else
country[i]._sort[3]=i+1;
}
//medal_people排序
sort(country,country+flag,cmp(MEDAL_PEOPLE));
country[0]._sort[4]=1;
for(int i=1;i<flag;i++)
{
if(country[i].medal_people==country[i-1].medal_people)
country[i]._sort[4]=country[i-1]._sort[4];
else
country[i]._sort[4]=i+1;
}
//按照国家序号重排
sort(country,country+flag,cmp(NUMBLE));
for(int i=0;i<flag;i++)
{
int _min=5;
int choice;
for(int j=1;j<5;j++)
{
if(_min>country[i]._sort[j])
{
_min=country[i]._sort[j];
choice=j;
}
}
printf("%d:%d\n",_min,choice);
}
cout<<endl;
}
return 0;
}