11.30总结
Confused_Konjac · · 个人记录
二维差分前缀和
参考 《二维前缀和总结》 与 《一维差分》
增加
int x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
a[x1][y1] ++;
a[x2 + 1][y1] --;
a[x1][y2 + 1] --;
a[x2 + 1][y2 + 1] ++;
变成前缀和
a[i][j] += a[i - 1][j];
a[i][j] += a[i][j - 1];
a[i][j] -= a[i - 1][j - 1];
P1083 [NOIP 2012 提高组] 借教室
题意
有
思路
使用二分答案来找到第一个无法满足的订单。对于每个猜测的订单数量
解题步骤
- 读入每天可用教室数量和所有订单信息
- 二分查找第一个无法满足的订单
- 对于每个
mid ,用差分数组计算前mid 个订单的教室使用情况 - 检查是否有某天教室使用量超过可用量
- 根据二分结果输出答案
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e6 + 10;
int n,m,ans,r[N],c[N];
struct node{
int s,t,d;
}a[N];
bool dick(int mid) {
for(int i = 1;i <= mid;i ++) {
c[a[i].s] += a[i].d;
c[a[i].t + 1] -= a[i].d;
}
for(int i = 1;i <= n;i ++) {
c[i] += c[i - 1];
if(c[i] > r[i]) return false;
}
return true;
}
signed main() {
cin >> n >> m;
for(int i = 1;i <= n;i ++) {
cin >> r[i];
}
for(int i = 1;i <= m;i ++) {
cin >> a[i].d >> a[i].s >> a[i].t;
}
int l = 0,r = m + 1;
while(l + 1 < r) {
int mid = (l + r) / 2;
if(dick(mid)) {
ans = mid;
l = mid;
}else {
r = mid;
}
for(int i = 1;i <= n;i ++) {
c[i] = 0;
}
}
if(ans == m) cout << 0 << endl;
else {
cout << -1 << endl;
cout << ans + 1 << endl;
}
}
P1672 [USACO05FEB] Feed Accounting S
题意
约翰有
思路
使用差分数组记录每天牛吃饲料的数量变化,然后计算前缀和得到每天消耗的饲料量。从第
解题步骤
- 用差分数组记录每头牛吃饲料的时间段
- 计算前缀和得到每天实际消耗的饲料量
- 从第
D 天开始倒推,累加每天的消耗量 - 当累计消耗量等于运来饲料与剩余饲料的差值时,输出当前天数
Code
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 10;
int d[N],sum[N],c,f1,f2,D,ans;
signed main() {
cin >> c >> f1 >> f2 >> D;
for(int i = 1;i <= c;i ++) {
int x,y;
cin >> x >> y;
d[x] ++;
d[y + 1] --;
}
for(int i = 1;i <= D;i ++) {
sum[i] = sum[i - 1] + d[i];
}
for(int i = D;i >= 1;i --) {
ans += sum[i];
if(ans == f1 - f2) {
cout << i;
break;
}
}
}