贪心 填数找中位数

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,判断全部填充1和是否大于x
  2. 中位数<=y

贪心 填数找中位数_第2张图片

  • d>n-k,那么右边全填充y也没用,中位数不可能>=y
  • d<=n-k右填充y直到d长度全为y,左边填充1,判断是否sum>x
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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>tmp;
		sum+=tmp;
		if(tmp>=y){
			cnt++;
		}
	}
	if(cnt<=n/2){//中位数小于y
		int d=(n+1)/2-cnt;//d为中位数到y相差的数目
		if(n-kx){
				cout<<-1<x){
			cout<<-1<

你可能感兴趣的:(算法实例)