Description
Solution
请围观lhx大佬的博客(大佬写的太好了我都没有写的动力了em)
Code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
int n,k;
int a[],b[];
ll sum[];
int L[],R[],t[];
ll dp[]; int tag[];
void downtag(int k)
{
tag[k<<]=tag[k<<|]=tag[k];
tag[k]=;
}
void modify(int k,int l,int r,int askx,int asky,int x)
{
if (askx>asky) return;
if (askx<=l&&r<=asky) {tag[k]=x;return;}
int mid=(l+r)/;
if (tag[k]) downtag(k);
if (askx<=mid) modify(k<<,l,mid,askx,asky,x);
if (mid<asky) modify(k<<|,mid+,r,askx,asky,x);
}
int query(int k,int l,int r,int x)
{
if (l==r) return tag[k];
int mid=(l+r)/;
if (tag[k]) downtag(k);
if (mid>=x) return query(k<<,l,mid,x);
else return query(k<<|,mid+,r,x);
}
int cnt;
ll solve(int x){
int re=query(,,cnt,x);
if (!re) return ;
return dp[re]+((long long)t[L[re]]-t[x]+k)%k;
}
int main()
{
scanf("%d%d",&n,&k);
for (int i=;i<=n;i++)
{
scanf("%d%d",&a[i],&b[i]);
sum[i]=a[i]+sum[i-];
if (b[i]!=) continue;
if (*a[i]>k) {puts("-1");return ;}
}
for (int i=;i<=n;i++)
{
if (b[i]==)
{
L[i]=(-*sum[i-]%k+k)%k;
R[i]=(-*sum[i]%k+k)%k;
}else L[i]=,R[i]=k-;
t[i*-]=L[i],t[i*]=R[i];
}
sort(t+,t+*n+);
cnt=unique(t+,t+*n+)-t-;
for (int i=n;i;i--)
{
L[i]=lower_bound(t+,t+cnt+,L[i])-t;
R[i]=lower_bound(t+,t+cnt+,R[i])-t;
dp[i]=solve(L[i]);
if (L[i]>R[i]) modify(,,cnt,R[i]+,L[i]-,i);
else modify(,,cnt,,L[i]-,i),modify(,,cnt,R[i]+,cnt,i);
}
ll ans=1e14;
for (int i=;i<=cnt;i++) ans=min(ans,solve(i));
printf("%lld",ans+*sum[n]);
}