当前位置:网站首页>[Luogu] P1083 [NOIP2012 提高组] 借教室(差分)
[Luogu] P1083 [NOIP2012 提高组] 借教室(差分)
2022-06-22 09:18:00 【Lupin123123】
一开始用线段树做的,后来还听说能二分+差分?! 线段树解法
说到差分真是气人,今天耗死在一道查分的字符串计数的题目上了。关于差分
定义差分数组dif[],dif[i]=a[i]-a[i-1]。如果要对[L,R]每个数加k并且需要单点查询,只要dif[L]+=k,dif[R+1]-=k。单点查询对dif数组求和实现,时间复杂度 O ( n ) O(n) O(n)
总而言之,差分可以实现 O ( 1 ) O(1) O(1)区间加减, O ( n ) O(n) O(n)单点查询。
完整代码:
#include<bits/stdc++.h>
#define FAST ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define INF 0x3f3f3f3f
typedef long long ll;
const int maxn = 1e6+5;
using namespace std;
int n,m,l,r,ans;
int a[maxn],dif[maxn],s[maxn],e[maxn],d[maxn];
int check(int x)
{
memset(dif,0,sizeof(dif));
for (int i=1; i<=n; i++) dif[i]=a[i]-a[i-1];
for (int i=1; i<=x; i++)
{
dif[s[i]]-=d[i];
dif[e[i]+1]+=d[i];
}
int sum=0;
for (int i=1; i<=n; i++)
{
sum+=dif[i];
if (sum<0) return 1;
}
return 0;
}
int main()
{
FAST;
cin>>n>>m;
for (int i=1; i<=n; i++) cin>>a[i];
for (int i=1; i<=m; i++) cin>>d[i]>>s[i]>>e[i];
l=0, r=n+1;
int flag=1;
while(l<=r)
{
int mid=(l+r)/2;
if (check(mid))
{
flag=0;
ans=mid;
r=mid-1;
}
else l=mid+1;
}
if (flag==0)
{
cout<<-1<<endl;
cout<<ans<<endl;
}
else cout<<0<<endl;
return 0;
}
边栏推荐
猜你喜欢

Sound and shadow 2022 heavy release! Detailed explanation of the new functions of Huisheng Huiying 2022

VMware installation Kali
![[network security officer] an attack technology that needs to be understood - high hidden and high persistent threats](/img/c9/c0ee95e816cac698f5397cc369d9ec.jpg)
[network security officer] an attack technology that needs to be understood - high hidden and high persistent threats

Summary and future prospect of transfer learning | community essay solicitation

Common SQL statements in MySQL

How C processes use non static methods

機器學習|nltk_Data下載錯誤|nltk的stopwords語料下載錯誤解决方法

Byte/byte? Don't get dizzy!

Langchao state-owned assets cloud: state-owned assets as a guide to help state-owned enterprises use data to enrich their wisdom in the cloud

支付-订单案例构建
随机推荐
HDU - 7072 双端队列+对顶
变量那些事
支付-订单案例构建
Alibaba big fish SMS interface PHP version, simplified version Alibaba big fish SMS sending interface PHP instance
Mapping multiple exit servers on ENSP
[node] node+ SMS API to realize verification code login
Machine learning | nltk_ Data download error |nltk's stopwords corpus download error solution
循环队列超详细实现,小白秒懂
C语言刷题 | 判断某年是否只闰年(15)
copy_from_user和copy_to_user
[cmake命令笔记]target_compile_options
Why use gradient descent method
稀疏数组^创建^还原^存盘^取盘--全家桶
C语言刷题 | 判断某年是否只闰年(12)
Quick search system (aso+xls) v1.0
一个老开源人的自述-如何干好开源这件事
It is hoped that more and more women will engage in scientific and technological work
机器学习|nltk_Data下载错误|nltk的stopwords语料下载错误解决方法
[hdu] P7079 Pty loves lines
Project optimization + online (Master?)