# 洛谷P4155：[SCOI2015]国旗计划 （贪心+倍增）

CODE：

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<stdio.h>
#include<algorithm>
using namespace std;

const int maxn=400100;
const int maxl=25;

struct data
{
int L,R,id;
} qj[maxn<<1];
int cur=0;

int Next[maxn<<1][maxl];
int ans[maxn];
int n,m;

bool Comp(data x,data y)
{
return x.L<y.L;
}

int main()
{
freopen("B.in","r",stdin);
freopen("B.out","w",stdout);

scanf("%d%d",&n,&m);
for (int i=1; i<=n; i++)
{
int c,d;
scanf("%d%d",&c,&d);
if (c<=d)
{
cur++;
qj[cur].L=c;
qj[cur].R=d;
qj[cur].id=i;
cur++;
qj[cur].L=m+c;
qj[cur].R=m+d;
}
else
{
cur++;
qj[cur].L=c;
qj[cur].R=m+d;
qj[cur].id=i;
cur++;
qj[cur].L=m+c;
qj[cur].R=m+m+d;
}
}

sort(qj+1,qj+cur+1,Comp);
int k=1;
for (int i=1; i<=cur; i++)
{
while ( k<cur && qj[k+1].L<=qj[i].R ) k++;
Next[i][0]=k;
}

for (int j=1; j<maxl; j++)
for (int i=1; i<=cur; i++)
Next[i][j]=Next[ Next[i][j-1] ][j-1];

for (int i=1; i<=cur; i++) if (qj[i].id)
{
int x=i,y=qj[i].id;
for (int j=maxl-1; j>=0; j--)
if (qj[ Next[x][j] ].R-m<qj[i].L) //!!!
x=Next[x][j],ans[y]+=(1<<j);
ans[y]+=2;
}
for (int i=1; i<=n; i++) printf("%d ",ans[i]);
printf("\n");

return 0;
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客