int l = 0,r = len-1;
while (l <= r){
int m = (l+r)>>1;
if (judge(m))l = m+1;
else r = m-1;
}
cout << l-1 << endl;
Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.
FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called "fajomonths". Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.
FJ's goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.
Input
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Sample Input
7 5 100 400 300 100 500 101 400
Sample Output
500
Hint
// 目标找到第一个大于等于所分组的条件
#include <iostream>
using namespace std;
const int MAXN = (int)1e5+7;
int a[MAXN];
int N,P;
//x 偏大则返回 true (x >= result)
bool Fit(int x){
int sum = 0,team = 1;
for (int i = 0;i < N;i ++){
if (sum + a[i] > x){
team ++;
i --;
sum = 0;
}else {
sum += a[i];
}
if (team > P) {
return false;
} //分组过多说明x偏小
}
return true; //返回x >= result的情况
}
int FindFirMax(){
int l = 0,r = 1e9;
while (l <= r){
int m = l + ((r-l)>>1);
if (Fit(m))r = m-1;
else l = m+1;
}
return l;
}
int main()
{
ios::sync_with_stdio(false);
cin >> N >> P;
for (int i = 0;i < N;i ++)cin >> a[i];
int ans = FindFirMax();
cout << ans << endl;
}
A
NanoApe 心痒痒又玩起了数列。他在纸上随便写了一个长度为n 的数列,他又根据心情写下了一个数 m。他想知道这个数列中有多少个区间里的第 k 大的数不小于 m,当然首先这个区间必须至少要有 kkk 个数啦。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MAXN = (ll)2e5+7;
ll Sum[MAXN];
ll N,M,K;
bool Judge(ll l,ll r){
if (Sum[r] - Sum[l-1] >= K)return true;
return false;
}
int main()
{
ios::sync_with_stdio(false);
ll T;
cin >> T;
while (T --){
cin >> N >> M >> K;
memset(Sum,0,sizeof(Sum));
ll tem;
for (ll i = 1;i <= N;i ++){
cin >> tem;
Sum[i] += Sum[i-1] + (tem >= M ? 1 : 0);
}
ll ans = 0;
for (ll i = 1;i+K-1 <= N;i ++){
ll l = i,r = N;
while (l <= r){
//jia
//cout << "l = " << l << ",r = " << r << endl;
ll m = (l+r)>>1;
if (Judge(i,m)) r = m-1;
else l = m+1;
}
//jia
//cout << "i = " << i << ",ans + " << N-l+1 << endl;
ans += N-l+1;
}
cout << ans << endl;
}
}
/*
2
7 4 2
4 2 7 7 6 5 1
7 2 1
1 1 1 1 1 1 1
*/