mirror of
https://github.com/renbaoshuo/202401-programming-assignments.git
synced 2024-11-27 08:26:20 +00:00
60 lines
1.3 KiB
Markdown
60 lines
1.3 KiB
Markdown
|
# 6-4 分治法求解金块问题
|
|||
|
|
|||
|
老板有一袋金块(共n块,2≤n≤100),两名最优秀的雇员每人可以得到其中的一块,排名第一的得到最重的金块,排名第二的则得到袋子中最轻的金块。
|
|||
|
|
|||
|
输入一个正整数$$N$$($$2\le N\le 100$$)和$$N$$个整数,用分治法求出最重金块和最轻金块。
|
|||
|
|
|||
|
本题要求实现2个函数,分别使用分治法在数组中找出最大值、最小值。
|
|||
|
|
|||
|
### 函数接口定义:
|
|||
|
```c++
|
|||
|
int max(int a[ ], int m, int n);
|
|||
|
int min(int a[ ], int m, int n);
|
|||
|
```
|
|||
|
递归函数`max`用分治法求出a[m]~a[n]中的最大值并返回。
|
|||
|
|
|||
|
递归函数`min`用分治法求出a[m]~a[n]中的最小值并返回。
|
|||
|
|
|||
|
### 裁判测试程序样例:
|
|||
|
```c++
|
|||
|
#include <stdio.h>
|
|||
|
#define MAXN 101
|
|||
|
|
|||
|
int max(int a[ ], int m, int n);
|
|||
|
int min(int a[ ], int m, int n);
|
|||
|
|
|||
|
int main(void)
|
|||
|
{
|
|||
|
int i, n;
|
|||
|
int a[MAXN];
|
|||
|
|
|||
|
scanf ("%d", &n);
|
|||
|
if(n >= 2 && n <= MAXN-1 ){
|
|||
|
for(i = 0; i < n; i++){
|
|||
|
scanf ("%d", &a[i]);
|
|||
|
}
|
|||
|
printf("max = %d\n", max(a, 0, n-1));
|
|||
|
printf("min = %d\n", min(a, 0, n-1));
|
|||
|
}else{
|
|||
|
printf("Invalid Value.\n");
|
|||
|
}
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
/* 请在这里填写答案 */
|
|||
|
```
|
|||
|
|
|||
|
### 输入样例:
|
|||
|
```in
|
|||
|
6
|
|||
|
3 9 4 9 2 4
|
|||
|
```
|
|||
|
|
|||
|
### 输出样例:
|
|||
|
```out
|
|||
|
max = 9
|
|||
|
min = 2
|
|||
|
```
|