BZOJ4444 SCOI2015國旗計劃(貪心+倍增)
阿新 • • 發佈:2018-10-30
algorithm || end getc sort tdi sco color ==
鏈上問題是一個經典的貪心。於是考慮破環成鏈,將鏈倍長。求出每個線段右邊能作為後繼的最遠線段,然後倍增即可。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<‘0‘||c>‘9‘) {if(c==‘-‘) f=-1;c=getchar();} while (c>=‘0‘&&c<=‘9‘) x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 200010 int n,m,ans[N],f[N<<1][20]; struct data{int l,r,i; }a[N<<1]; bool cmp(const data&a,const data&b) { return a.l<b.l; } int main() { #ifndef ONLINE_JUDGE freopen("bzoj4444.in","r",stdin); freopen("bzoj4444.out","w",stdout); const char LL[]="%I64d\n"; #else const char LL[]="%lld\n"; #endif n=read(),m=read(); for (int i=1;i<=n;i++) { a[i].l=read(),a[i].r=read(),a[i].i=i; if (a[i].l>a[i].r) a[i].r+=m; } sort(a+1,a+n+1,cmp); for (int i=n+1;i<=n*2;i++) a[i].l=a[i-n].l+m,a[i].r=min(m*2,a[i-n].r+m),a[i].i=a[i-n].i; int t=1; for (int i=1;i<=n*2;i++) { while (t<n*2&&a[t+1].l<=a[i].r) t++; f[i][0]=t; } for (int j=1;j<20;j++) for (int i=1;i<=n*2;i++) f[i][j]=f[f[i][j-1]][j-1]; for (int i=1;i<=n;i++) { int x=i,cnt=1; for (int j=19;~j;j--) if (f[x][j]-i<n) cnt+=1<<j,x=f[x][j]; ans[a[i].i]=cnt; } for (int i=1;i<=n;i++) printf("%d ",ans[i]); return 0; }
BZOJ4444 SCOI2015國旗計劃(貪心+倍增)