将军的问题

一、问题:

1、Question requirements

After a difficult battle, the general decided to reward the officers under his opponent. The rules were as follows: the general and each subordinate officer wrote a number on their left and right hands, and then these officers were arranged in sequence. The general stood at the head of the team, and each officer received a reward equal to the product of the numbers on their left hands divided by the numbers on their right hands. The result was rounded down to avoid an officer receiving too much reward, We need to adjust the queue of officers. Please design a program to implement and output the arrangement of officers, so that the officer who may receive the highest reward receives the least reward, and output the minimum value.

2、Data value range

Number of award-winning officers: [1,100]

Number on hand: [010000]

3、Resource requirements

Running time:<1s;

Memory usage:<32768kB;

4、Application scenarios

Task queue management

5、target:
Use C language to solve this problem and give me the code

2、代码:

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

typedef struct {
	int left_hand;
	int right_hand;
	double ratio;
} Officer;

int compare(const void* a, const void* b) {
	Officer* officerA = (Officer*)a;
	Officer* officerB = (Officer*)b;
	if (officerA->ratio < officerB->ratio) return 1;
	if (officerA->ratio > officerB->ratio) return -1;

	return 0;
}
int main() {
	int numberOfOfficers;
	//输入军官数量
	scanf_s("%d", &numberOfOfficers);
	Officer officers[100]; //根据问题陈述,假设最多100名官员
	for (int i = 0; i < numberOfOfficers; i++) {
		//输入每个军官左手以及右手的数量
		scanf_s("%d %d", &officers[i].left_hand, &officers[i].right_hand);
		officers[i].ratio = (double)officers[i].left_hand / officers[i].right_hand;
	}
	qsort(officers, numberOfOfficers, sizeof(Officer), compare);
	int minimumReward = (int)(officers[0].left_hand / officers[0].right_hand);
	for (int i = 1; i < numberOfOfficers; i++) {
		int reward = (int)(officers[i].left_hand / officers[i].right_hand);
		if (reward < minimumReward) {
			minimumReward = reward;
		}
	}

	printf("最低奖励为: %d\n", minimumReward);
	printf("军官的命令是: \n");
	for (int i = 0; i < numberOfOfficers; i++) {
		printf("军官 %d: 左手 = %d, 右手 = %d,比例 = %.2f\n", i + 1, officers[i].left_hand, officers[i].right_hand, officers[i].ratio);
	}

	return 0;
}

3、运行:

输入:

3
10 5
20 4
30 3

输出:

最低奖励为: 2
军官的命令是: 
Officers 1: Left Hand = 30, Right Hand = 3, Ratio = 10.00
Officers 2: Left Hand = 20, Right Hand = 4, Ratio = 5.00
Officers 3: Left Hand = 10, Right Hand = 5, Ratio = 2.00
posted @ 2023-12-19 17:21  news_one  阅读(7)  评论(0编辑  收藏  举报