变态最大值
2017-06-24 12:36
169 查看
变态最大值
时间限制:1000 ms | 内存限制:65535 KB难度:1
描述
Yougth讲课的时候考察了一下求三个数最大值这个问题,没想到大家掌握的这么烂,幸好在他的帮助下大家算是解决了这个问题,但是问题又来了。
他想在一组数中找一个数,这个数可以不是这组数中的最大的,但是要是相对比较大的,但是满足这个条件的数太多了,怎么办呢?他想到了一个办法,把这一组数从开始把每相邻三个数分成一组(组数是从1开始),奇数组的求最大值,偶数组的求最小值,然后找出这些值中的最大值。
输入有多组测试数据,以文件结束符为标志。
每组测试数据首先一个N,是数组中数的个数。(0<N<10000,为降低题目难度,N是3的倍数)
然后是数组中的这些数。
输出输出包括一行,就是其中的最大值。
样例输入
3 4 5 6 6 1 2 3 7 9 5
样例输出
6 5
来源Yougth原创
上传者TC_杨闯亮
问题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=811
问题分析:
按照规则,可以先求出每个奇数组的最大值,然后在这些值中选择最大的,然后再求出每个偶数组中的最小值,在这些最小值中选出最大的,
最后这两个数比较选出最大的即可。
代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> #include <iomanip> #define MAX 10000 using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int max(int a,int b,int c){ if(a>b){ if(a>c){ return a; }else{ return c; } } if(b>a){ if(b>c){ return b; }else{ return c; } } } int min(int a,int b,int c){ if(a<b){ if(a<c){ return a; }else{ return c; } }else{ if(b<c){ return b; }else{ return c; } } } int main(int argc, char** argv) { /*freopen("file/input.txt","r",stdin); freopen("file/output.txt","w",stdout);*/ int n; while(scanf("%d",&n)!=EOF){ //1.输入n个数 int num[MAX]; for(int i=0;i<n;i++){ scanf("%d",&num[i]); } //2.分组,奇数组找最大值 偶数组找最小值 int ans=-1; //先在奇数组中的所有最大值找打最大的那个 for(int i=0;i<n;i+=6) { //奇数组 int maxnum=max(num[i],num[i+1],num[i+2]); if(maxnum>ans){ ans=maxnum; } } //再找出偶数组中所有最小值中的最大的那个 for(int i=3;i<n;i+=6) { //偶数组 int minnum=min(num[i],num[i+1],num[i+2]); if(minnum>ans){ ans=minnum; } } printf("%d\n",ans); } return 0; }
优秀代码:
01.
#include <cstdio>
02.
#define Max(a,b,c) a>( 16325 b>c?b:c)?a:(b>c?b:c)
03.
#define Min(a,b,c) a>(b>c?c:b)?(b>c?c:b):a
04.
int
main()
05.
{
06.
int
a[10005];
07.
int
n,i,j,h;
08.
while
(~
scanf
(
"%d"
,&n))
09.
{
10.
int
max=1<<32;
11.
for
(i=0;i<n&&
scanf
(
"%d"
,&a[i]);i++){}
12.
for
(i=0;i<n;i+=3){
13.
h=i%2==0?Max(a[i],a[i+1],a[i+2]):Min(a[i],a[i+1],a[i+2]);
14.
max=h>max?h:max;
15.
}
16.
printf
(
"%d\n"
,max);
17.
}
18.
return
0;
19.
}
对比分析:
1.在对奇数组和偶数组求分别求最大和最小时可以合并到一个循环中。
我写了79行,优秀就19行。