# [JOISC2017 D2 T1]Arranging Tickets

n<=2e5,m<=1e5

r也是同理

### Code

#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;

typedef long long ll;

char ch;
for(ch=getchar();ch<'0'||ch>'9';ch=getchar());
int x=ch-'0';
for(ch=getchar();ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x;
}

const int N=2e5+5;

struct node{int l,r;ll c;}p[N];

int n,m;
ll a[N],tag[N];

vector<pair<int,ll> > vec[N];
priority_queue<pair<int,ll> > q;
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)

bool judge(ll ans,int t,ll cnt) {
if (ans<cnt) return 0;
fo(i,1,n) tag[i]=0,vec[i].clear();
fo(i,1,m) if (p[i].l<=t&&p[i].r>t) vec[p[i].l].pb(mp(p[i].r,p[i].c));
while (!q.empty()) q.pop();
int j=0;ll now=0;
fo(i,1,t) {
for(int j=0;j<vec[i].size();j++) q.push(vec[i][j]);
while (a[i]-now+cnt>ans) {
if (q.empty()) return 0;
pair<int,ll> tmp=q.top();q.pop();
ll ret=min(tmp.second,(a[i]-now+cnt-ans+1)/2);
now+=ret;cnt-=ret;
tag[tmp.first]+=ret*2;
if (tmp.second!=ret) q.push(mp(tmp.first,tmp.second-ret));
}
}
tag[t+1]-=now;
fo(i,t+1,n) {
tag[i]+=tag[i-1];
if (tag[i]+a[i]>ans) return 0;
}
return 1;
}

bool check(ll ans,int t) {return judge(ans,t,a[t]-ans)||judge(ans,t,a[t]-ans+1);}

int main() {
ll l=0,r=0;
fo(i,1,m) {
if (p[i].l>p[i].r) swap(p[i].l,p[i].r);
a[p[i].l]+=p[i].c;a[p[i].r]-=p[i].c;r+=p[i].c;
}
fo(i,1,n) a[i]+=a[i-1];
int tl=0,tr=0;
fo(i,1,n) {
if (a[i]>a[tl]) tl=i;
if (a[i]>=a[tr]) tr=i;
}
while (l<r) {
ll mid=l+r>>1;
if (check(mid,tl)||check(mid,tr)) r=mid;
else l=mid+1;
}
printf("%lld\n",l);
return 0;
}

02-26 526
01-07 222

09-18 283
09-07 645
04-16 35
07-05 531