找到可行区间,最优解一定在区间的下端点。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxn 500500 using namespace std; int n,X,x[maxn],a[maxn],b[maxn],l[maxn],r[maxn],ans=0; int read() { char ch;int data=0,f=1; while (ch<'0' || ch>'9') {if (ch=='-') f=-1;ch=getchar();} while (ch>='0' && ch<='9') { data=data*10+ch-'0'; ch=getchar(); } return data*f; } int main() { n=read();X=read(); for (int i=1;i<=n;i++) x[i]=read(),a[i]=read(),b[i]=read(); l[0]=r[0]=0; for (int i=1;i<=n;i++) { l[i]=max(l[i-1]-(x[i]-x[i-1]),a[i]+1); r[i]=min(r[i-1]+(x[i]-x[i-1]),b[i]-1); if (l[i]>r[i]) {printf("NIE ");return 0;} } int ret=0; for (int i=1;i<=n;i++) { if (x[i]>X) break; int now=x[i]-x[i-1]+l[i]-ret; if (now%2) {l[i]++;now++;} if (l[i]>r[i]) {printf("NIE ");return 0;} if (now>0) ans+=now/2;ret=l[i]; } printf("%d ",ans); return 0; }