PAT (Basic Level) Practice 1082 射击比赛 (20 分)

本题目给出的射击比赛的规则非常简单,谁打的弹洞距离靶心最近,谁就是冠军;谁差得最远,谁就是菜鸟。本题给出一系列弹洞的平面坐标(x,y),请你编写程序找出冠军和菜鸟。我们假设靶心在原点(0,0)。

输入格式:

输入在第一行中给出一个正整数 N(≤ 10 000)。随后 N 行,每行按下列格式给出:

ID x y

其中 ID 是运动员的编号(由 4 位数字组成);x 和 y 是其打出的弹洞的平面坐标(x,y),均为整数,且 0 ≤ |x|, |y| ≤ 100。题目保证每个运动员的编号不重复,且每人只打 1 枪。

输出格式:

输出冠军和菜鸟的编号,中间空 1 格。题目保证他们是唯一的。

输入样例:

3
0001 5 7
1020 -1 3
0233 0 -1

输出样例:

0233 0001

代码实现:(采用快排)

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
using namespace std;

typedef struct Sport{
    char id[5];
    int x;
    int y;
}Sport;


void swap(Sport a[], int i, int j)
{
	Sport temp = a[i];
	a[i] = a[j];
	a[j] = temp;
}

//交换a[]中记录,使枢轴记录到位,并返回其所在位置
//此时在它之前(后)的记录均不大(小)于它
int partition(Sport a[], int low, int high)
{
	int pivotkey;
	pivotkey = sqrt(a[low].x*a[low].x+a[low].y*a[low].y);					//用数组的第一个记录作枢轴记录
	while (low < high)						//从数组的两端交替向中间扫描
	{
		while (low < high && sqrt(a[high].x*a[high].x+a[high].y*a[high].y) >= pivotkey)
			high--;
		swap(a, low, high);					//将枢轴记录小的记录交换到低端
		while (low < high && sqrt(a[low].x*a[low].x+a[low].y*a[low].y) <= pivotkey)
			low++;
		swap(a, low, high);					//将比枢轴记录大的记录交换到高端
	}
	return low;								//返回枢轴所在位置
}

void QSort(Sport a[], int low, int high)
{
	int pivot;
	if (low < high)
	{
		pivot = partition(a, low, high);	//将a[]一分为二
											//算出枢轴值pivot
		QSort(a, low, pivot-1);				//对低子表递归排序
		QSort(a, pivot+1, high);			//对高子表递归排序
	}

}


int main()
{
    int n;
    scanf("%d",&n);
    Sport sport[n];
    for(int i = 0;i < n;i++)
        scanf("%s%d%d",sport[i].id,&sport[i].x,&sport[i].y);
    QSort(sport,0,n-1);
    printf("%s %s\n",sport[0].id,sport[n-1].id);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Annfan123/article/details/86504417
今日推荐