(算法练习)——201903-1小中大(CCF模拟)

其实用优先队列这题更快?
AC代码:

#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;

int yuanshi[100000];
int linshi[100000];
double record[3];

int main(){
	int n;
	scanf("%d",&n);
	for(int i = 0;i <n;i++){
		scanf("%d",&yuanshi[i]);
		linshi[i] = yuanshi[i];
	} 
	sort(linshi,linshi+n);
	record[0] = (double)linshi[0];
	record[1] = (double)linshi[n-1];
	int t;
	double s;
	if(n %2 == 0){
		s = (double)(yuanshi[n/2] + yuanshi[n/2-1])/2;
		record[2] = s;
	}
	else{
		t = yuanshi[(n-1)/2];
		record[2] = (double)t;
	}
	sort(record,record+3);
	if((int)record[2] == record[2]){
		printf("%d ",(int)record[2]);
	}
	else{
		printf("%.1f ",record[2]);
	}
	if((int)record[1] == record[1]){
		printf("%d ",(int)record[1]);
	}
	else{
		printf("%.1f ",record[1]);
	}
	if((int)record[0] == record[0]){
		printf("%d ",(int)record[0]);
	}
	else{
		printf("%.1f ",record[0]);
	}
	
}

/*
4
-2 -1 3 4

3
-1 2 4

4
-17 -2 9 22 

*/

用了优先队列试试,并没有多快,反而时间空间耗得更多了。。。写着玩好了= =
AC代码

#include <stdio.h>
#include <queue>
#include <algorithm>
using namespace std;

priority_queue<double,vector<double>,less<double> >q;    //从大到小排序 
priority_queue<double,vector<double>,greater<double> >ai;   //从小到大排序 
priority_queue<double,vector<double>,less<double> >ans;  //从大到小排序 
int yuanshi[100000];

int main(){
	int n;
	int linshi;
	scanf("%d",&n);
	for(int i = 0;i <n;i++){
		scanf("%d",&linshi);
		yuanshi[i] = linshi;
		q.push((double)linshi);
		ai.push((double)linshi); 
	}
	ans.push(q.top());
	ans.push(ai.top());
	double Z;
	if(n %2 == 0){
		Z = (double)(yuanshi[n/2-1] + yuanshi[n/2])/2;
		ans.push(Z);
	}
	else{
		Z = (double)yuanshi[(n-1)/2];
		ans.push(Z);
	}
	double t;
	for(int i = 0;i<3;i++){
		t = ans.top();
		ans.pop();
		if((int)t == t){
			printf("%d ",(int)t);
		}
		else{
			printf("%.1f ",t);
		}
	}
}

/*
4
-2 -1 3 4

3
-1 2 4

4
-17 -2 9 22 

*/

无

发布了212 篇原创文章 · 获赞 6 · 访问量 6420

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104228908
今日推荐