二分答案的两个模板:
1.最小值的最大化:
#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
priority_queue<int, vector<int>, greater<int>> pq;
map<int, int>mp;
const int N = 2e6 + 10;
ll l, n, k;
ll a[N];
ll pd(int x)
{ll t = 0, cnt = 0;for (int i = 1; i <= n; i++){if (a[i] - t < x)cnt++;else{t = a[i];}}return cnt <= k;
}
ll cz(int ls, int r)
{while (ls < r){ll mid = (ls + r + 1) >> 1;if (pd(mid))ls = mid;elser = mid - 1;}return ls;
}
void solve()
{
}
int main()
{ios::sync_with_stdio(false);cin.tie(nullptr);cin >> l >> n >> k;for (int i = 1; i <= n; i++)cin >> a[i];ll ans = cz(0, l);cout << ans << endl;return 0;
}
2.最大值的最小化
#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
priority_queue<int, vector<int>, greater<int>> pq;
map<int, int>mp;
const int N = 2e6 + 10;
ll l, n, k;
ll a[N];
ll pd(int x)
{ll t = 0;if (x == 0)return 0;for (int i = 1; i <= n; i++){t += (a[i + 1] - a[i] - 1) / k;}return t <= k;
}
ll cz(int ls, int r)
{while (ls < r){ll mid = (ls + r) >> 1;if (pd(mid))r = mid;elsels = mid + 1;}return ls;
}
void solve()
{
}
int main()
{ios::sync_with_stdio(false);cin.tie(nullptr);cin >> l >> n >> k;for (int i = 1; i <= n; i++)cin >> a[i];ll ans = cz(0, l);cout << ans << endl;return 0;
}
A - Insert
代码:
void solve()
{cin >> n >> k >> x;vector<int>a(N);for (int i = 1; i <= n; i++)cin >> a[i];a.insert(a.begin() + k + 1, x);for (int i = 1; i <= n + 1; i++)cout << a[i] << " ";return;
}
P2512 [HAOI2008] 糖果传递 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题目虽少,难度却不小
推导如下:
求得全部的和sum,平均值ave=sum/n,如图我们可以看出
ave=a1+x1-x2=a2+x2-x3=a3+x3-x4=an+xn-x1
再推导:
x1=x1;
x2=a1+x1-ave;
......;
xn=(a1-ave)+...+(an-1-ave)+x1;
x1=x1+c1;
x2=x1+c2
xn=cn+x1;
可以得到cn,n=1时c1=0,n>1时cn=cn-1-an-1-1;
取中值时最大
AC:
#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
priority_queue<int, vector<int>, greater<int>> pq;
map<int, int>mp;
const int N = 2e6 + 10;
ll n;
ll a[N], c[N];
void solve()
{cin >> n;ll sum = 0;for (int i = 1; i <= n; i++){cin >> a[i];sum += a[i];}ll ave = sum / n;for (int i = 2; i <= n; i++){c[i] = c[i - 1] + a[i - 1] - ave;}ll ans = 0;sort(c + 1, c + 1 + n);for (int i = 1; i <= n; i++){ans += abs(c[1 + n >> 1] - c[i]);}cout << ans << endl;
}
int main()
{ios::sync_with_stdio(false);cin.tie(nullptr);solve();return 0;
}