贪心 填数找中位数

CodeForces 540B–填数找中位数

题意:

第一行 n,k,p,x,y,有n个任务,已经完成了k个任务,完成任务最大得分为p,最大得分总和是x,众多分数得分的中位数是y,问剩下的务该得多少分才能保证分数总和不大于x,而且中位数不小于y。如果不可能出现这种情况则输出-1。
分析
这里的贪心策略要使sum尽量小,在此基础上我们来考虑怎么是中位数>=y呢,最理想的情况就是中位数恰好是y,这样和最小,也满足其他条件。分析一下可知我们需要填充的数字应该是1,y,当我当前的中位数比y大的时候,添1;当我当前的中位数比y小的时候,添y。这样的选择能尽可能使中位数偏向于y,且使总和尽量小。如果采取这个策略仍然不能满足条件,那就不存在满足条件的解。下面分情况

  1. 中位数大于y
    在这里插入图片描述
    这个时候只能在左边填充1,判断全部填充1和是否大于x
  2. 中位数<=y

在这里插入图片描述

  • d>n-k,那么右边全填充y也没用,中位数不可能>=y
  • d<=n-k右填充y直到d长度全为y,左边填充1,判断是否sum>x
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
int main() 
{
	int n,k,p,x,y,sum=0;
	cin>>n>>k>>p>>x>>y;
	int tmp;
	int cnt=0;
	for(int i=0;i<k;i++){
		cin>>tmp;
		sum+=tmp;
		if(tmp>=y){
			cnt++;
		}
	}
	if(cnt<=n/2){//中位数小于y
		int d=(n+1)/2-cnt;//d为中位数到y相差的数目
		if(n-k<d){
			cout<<-1<<endl;
		}else{
			k+=d;
			sum+=y*d;
			sum+=n-k;
			if(sum>x){
				cout<<-1<<endl;
			}else{
				while(d--){
					cout<<y<<" ";
				}
				for(int i=0;i<n-k;i++){
					cout<<"1 ";
				}				
				cout<<endl;
			}
		}
	}else{//中位数大于y,前面全填充1
		sum+=n-k;
		if(sum>x){
			cout<<-1<<endl;
		}else{
			for(int i=0;i<n-k;i++){
				if(i){
					cout<<" ";
				}
				cout<<'1';
			}
			cout<<endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jianglw1/article/details/83047015