CodeForces 671B Robin Hood (二分)

题意:n个人,每个人ci的金币,每天最富有的人都会给最贫穷的人1金币,问k天后最富有人和最贫穷的人差了多少金币。

析:首先先这样想,如果每个穷人每天获得一个金币,那么k天后,最穷的人的金币为x,同理,每个富人每天丢一枚金币,那么k天后最富的人金币为y,

那么如果 x < y那么y-x就是答案,否则就要看金币能不能均分,也就是sum % n 是否为0,而x和y可能通过二分来求。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<double, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-5;
const int maxn = 5e5 + 10;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r >= 0 && r < n && c >= 0 && c < m;
}
int a[maxn];

bool judge(int mid){
  int t = m;
  for(int i = 0; i < n; ++i){
    if(a[i] >= mid) return true;
    t -= mid - a[i];
    if(t < 0)  return false;
  }
  return true;
}

int main(){
  scanf("%d %d", &n, &m);
  LL sum = 0;
  for(int i = 0; i < n; ++i){
    scanf("%d", a+i);
    sum += a[i];
  }
  sort(a, a + n);
  int l = 0, r = 2e9;
  while(l < r){
    int mid = l + (r-l+1)/2;
    if(judge(mid))  l = mid;
      else r = mid - 1;
  }
  int ans1 = l;
  for(int i = 0; i < n; ++i)  a[i] = mod - a[i];
  sort(a, a + n);
  l = 0, r = 2e9;
  while(l < r){
    int mid = l + (r-l+1)/2;
    if(judge(mid))  l = mid;
    else r = mid - 1;
  }
  int ans2 = mod - l;
  if(ans2 > ans1)  printf("%d
", ans2-ans1);
  else printf("%d
", sum % n != 0);
  return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/6490261.html