您的位置:首页 > 编程语言 > C语言/C++

c语言趣题之“选美比赛”

2014-12-30 15:42 323 查看
/*
在选美大奖赛的半决赛现场,有一批选手参加比赛,比赛的规则是最后的得分越高,名次越低。
当半决赛结束时,要在现场按照选手的出场顺序宣布最后得分和最后名次,获得相同分数的选手具有相同的名次,
名次连续编号,不要考虑同名次的选手人数。例如:
选手序号:1,2,3,4,5,6,7
选手得分:5,3,4,7,3,5,6
则输出名次为:3,1,2,5,1,3,4
请编程帮助大奖赛组委会完成半决赛的评分排名工作。

函数接口:void ScorePlace(int place[], const int score[], int num);
输入:存储选手名次的数组place[],存储选手得分的数组score[],选手人数num。
输出:存储选手名次的数组place[]。

示例1:
输入:score[] = {2,8,5,1,10,5,9,9};
输出:place[] = {2,4,3,1, 6,3,5,5};
示例2:
输入:score[] = {7,7,6,6,7};
输出:place[] = {2,2,1,1,2};
*/

#include <time.h>
#include<stdio.h>
#include<stdlib.h>

#define MAX 20000

typedef struct Player {
int rank; //排名
int sco; //成绩
} Player;

int Cmp(const void *a , const void *b);
void ScorePlace(int place[], const int score[], int num);
void ScorePlace_c(int place[], const int score[], int num);

int main()
{
int score[MAX] = {0};
int place1[MAX] = {0};
int place2[MAX] = {0};
int i, k, max;

// max = rand()%(MAX-10) + 10;

max = MAX;
for (i=0; i<max; i++)
score[i] = rand()%101 + 1;

ScorePlace_1(place1, score, max);
printf("p[%d] = %d\n", max-1, place1[max-1]);

ScorePlace_2(place2, score, max);
printf("p[%d] = %d\n", max-1, place2[max-1]);

return 0;
}

void ScorePlace_1(int place[], const int score[], int num)
{
int *sameScore;
int i, j, k, numPlace = 1;  //选手的名次

sameScore = (int *)malloc(sizeof(int) * num);
if (!sameScore)
{
puts("Error");
exit(1);
}

for (i=0; i<num; i++)//为每个选手的名次设初值为0,表示还未对其排名
place[i] = 0;

for (i=0; i<num; i++)//遍历数组,每次处理一个名次
{
if (place[i] == 0)//如果还未对该元素进行排名
{
int min = score[i]; //取该元素作为当前最小值
int same = 0;
sameScore[same] = i;//记录分值为min的(即具有相同名次)元素的下标

for (j=i+1; j<num; j++)//对余下元素进行处理
{
if (place[j] == 0)
{
if (score[j] < min)//若该元素比min小,取该元素作为当前最小值
{
min = score[j];
same = 0;  //重新记录分值为min的(即具有相同名次)元素的个数
sameScore[same] = j;
}
else if (score[j] == min)//若该元素等于min,则其属于具有相同名次的元素
{
sameScore[++same] = j; //记录分值为min的元素的下标
}
}
}
for (k=0; k<=same; k++)//对具有相同名次的元素进行排名
{
place[sameScore[k]] = numPlace;
}

numPlace++; //名次增一
i = -1; //重新查找下一个尚未排名的元素进行排名处理
}
}
free(sameScore);
}

int Cmp(const void *a , const void *b)
{
return ((Player *)a)->sco - ((Player *)b)->sco;
}

void ScorePlace_2(int place[], const int score[], int num)//使用快速排序对结构体数组排序,然后递增名次即可
{
int i;
Player *p;

p = (Player *)malloc(sizeof(Player) * num);
if (!p)
{
puts("Error");
exit(1);
}

for (i=0; i<num; i++)
{
p[i].rank = i;
p[i].sco = score[i];
}

qsort(p, num, sizeof(p[0]), Cmp);

place[p[0].rank] = 1;
for (i=1; i<num; i++)
{
if (p[i].sco == p[i-1].sco)
place[p[i].rank] = place[p[i-1].rank];
else
place[p[i].rank] = place[p[i-1].rank] + 1;
}
    free(p);}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: