最近等對 51Nod - 1571
阿新 • • 發佈:2018-12-12
https://www.51nod.com/Challenge/Problem.html#!#problemId=1571
媽的垃圾51nod 總是卡輸入輸出
把所有線段按左端點排序 作為第一維 右端點為第二維 cdq分治
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll N=0x3f3f3f3f3f3f3f3f; const int maxn=5e5+10; struct node { int tp,id,l,r; }; node order[2*maxn],tmp[2*maxn]; ll ans[maxn],ary[maxn],gou[maxn]; int book[maxn]; int n,q,tot; template <class T> inline void _cin(T &ret) //讀正負整數 (int, long long) { char ch; int flag = 0; while((ch = getchar()) < '0' || ch > '9') { if(ch == '-') flag = 1; } for(ret = 0; ch >= '0' && ch <= '9'; ch = getchar()) ret = ret * 10 + ch - '0'; if(flag) ret *= -1; } template <class T> inline void print_d(T x) { if (x > 9) { print_d(x / 10); } putchar(x % 10 + '0'); } bool cmp(node n1,node n2) { if(n1.l==n2.l){ if(n1.r==n2.r) return n1.tp>n2.tp; else return n1.r>n2.r; } else return n1.l<n2.l; } void cdq(int l,int r) { ll minn; int m,i,p,q; if(l==r) return; m=(l+r)/2; cdq(l,m),cdq(m+1,r); i=l,p=l,q=m+1,minn=N; while(p<=m&&q<=r){ if(order[p].r>=order[q].r){ if(order[q].tp==1) minn=min(minn,(ll)(order[q].r-order[q].l)); tmp[i++]=order[q++]; } else{ if(order[p].tp==2) ans[order[p].id]=min(ans[order[p].id],minn); tmp[i++]=order[p++]; } } while(p<=m){ if(order[p].tp==2) ans[order[p].id]=min(ans[order[p].id],minn); tmp[i++]=order[p++]; } while(q<=r){ tmp[i++]=order[q++]; } for(i=l;i<=r;i++) order[i]=tmp[i]; } int main() { int i,val,l,r; _cin(n),_cin(q); for(i=1;i<=n;i++){ _cin(val); ary[i]=val,gou[i]=val; } sort(gou+1,gou+n+1); tot=unique(gou+1,gou+n+1)-gou-1; for(i=1;i<=n;i++) ary[i]=lower_bound(gou+1,gou+tot+1,ary[i])-gou; for(i=1;i<=n;i++){ if(book[ary[i]]!=0){ tot++; order[tot].tp=1,order[tot].l=book[ary[i]],order[tot].r=i; } book[ary[i]]=i; } for(i=1;i<=q;i++){ _cin(l),_cin(r); tot++; order[tot].tp=2,order[tot].id=i,order[tot].l=l,order[tot].r=r; } sort(order+1,order+tot+1,cmp); for(i=1;i<=q;i++) ans[i]=N; cdq(1,tot); for(i=1;i<=q;i++){ if(ans[i]==N) puts("-1"); else{ print_d(ans[i]); puts(""); } } return 0; } /* 5 3 1 2 3 1 2 1 1 2 2 1 5 */