任意门:http://codeforces.com/gym/101954/problem/E
AC code:
1 #include <bits/stdc++.h> 2 #define inc(i, j, k) for(int i = j; i <= k; i++) 3 #define rep(i, j, k) for(int i = j; i < k; i++) 4 #define F(x) ((x)/3+((x)%3==1?0:tb)) 5 #define G(x) ((x)<tb?(x)*3+1:((x)-tb)*3+2) 6 #define INF 0x3f3f3f3f 7 #define LL long long 8 using namespace std; 9 const int maxn = int(3e6)+10;///注意空间是要开到 3N 的 10 //const int N = maxn; 11 12 #define F(x) ((x)/3+((x)%3==1?0:tb)) 13 #define G(x) ((x)<tb?(x)*3+1:((x)-tb)*3+2) 14 int wa[maxn],wb[maxn],wv[maxn],Ws[maxn]; 15 int r[maxn], sa[maxn], Rank[maxn], height[maxn]; 16 17 int c0(int *r,int a,int b) 18 {return r[a]==r[b]&&r[a+1]==r[b+1]&&r[a+2]==r[b+2];} 19 20 int c12(int k,int *r,int a,int b) 21 {if(k==2) return r[a]<r[b]||r[a]==r[b]&&c12(1,r,a+1,b+1); 22 else return r[a]<r[b]||r[a]==r[b]&&wv[a+1]<wv[b+1];} 23 24 void Sort(int *r,int *a,int *b,int n,int m) 25 { 26 int i; 27 for(i=0;i<n;i++) wv[i]=r[a[i]]; 28 for(i=0;i<m;i++) Ws[i]=0; 29 for(i=0;i<n;i++) Ws[wv[i]]++; 30 for(i=1;i<m;i++) Ws[i]+=Ws[i-1]; 31 for(i=n-1;i>=0;i--) b[--Ws[wv[i]]]=a[i]; 32 return; 33 } 34 void dc3(int *r,int *sa,int n,int m) //涵义与DA 相同 35 { 36 int i,j,*rn=r+n,*san=sa+n,ta=0,tb=(n+1)/3,tbc=0,p; 37 r[n]=r[n+1]=0; 38 for(i=0;i<n;i++) if(i%3!=0) wa[tbc++]=i; 39 Sort(r+2,wa,wb,tbc,m); 40 Sort(r+1,wb,wa,tbc,m); 41 Sort(r,wa,wb,tbc,m); 42 for(p=1,rn[F(wb[0])]=0,i=1;i<tbc;i++) 43 rn[F(wb[i])]=c0(r,wb[i-1],wb[i])?p-1:p++; 44 if(p<tbc) dc3(rn,san,tbc,p); 45 else for(i=0;i<tbc;i++) san[rn[i]]=i; 46 for(i=0;i<tbc;i++) if(san[i]<tb) wb[ta++]=san[i]*3; 47 if(n%3==1) wb[ta++]=n-1; 48 Sort(r,wb,wa,ta,m); 49 for(i=0;i<tbc;i++) wv[wb[i]=G(san[i])]=i; 50 for(i=0,j=0,p=0;i<ta && j<tbc;p++) 51 sa[p]=c12(wb[j]%3,r,wa[i],wb[j])?wa[i++]:wb[j++]; 52 for(;i<ta;p++) sa[p]=wa[i++]; 53 for(;j<tbc;p++) sa[p]=wb[j++]; 54 return; 55 } 56 57 void calheight(int *r, int *sa, int n) 58 { 59 int i, j, k = 0; 60 for(i = 1; i <= n; i++) Rank[sa[i]] = i; 61 for(i = 0; i < n; height[Rank[i++]] = k) 62 for(k?k--:0,j=sa[Rank[i]-1]; r[i+k]==r[j+k]; k++) 63 return; 64 } 65 66 67 int N, K; 68 string str; 69 70 bool check(int t) 71 { 72 int b = 0, e = -1; 73 for(int i = 0; i < N; i++){ 74 if(Rank[i] > t) continue; 75 if(e < i) b = i; 76 e = i+K; 77 if(e-b >= N) return true; 78 } 79 return false; 80 } 81 82 int main() 83 { 84 scanf("%d %d", &N, &K); 85 cin >> str; 86 str+=str; 87 // cout << str << endl; 88 int n_len = str.size(); 89 for(int i = 0; i < n_len; i++){ 90 r[i] = str[i]-'a'+1; 91 } 92 // n_len--; 93 r[n_len] = 0; 94 dc3(r, sa, n_len+1, 30); 95 calheight(r, sa, n_len); 96 // for(int i = 0; i < n_len; i++) cout << Rank[i] << endl; 97 98 int L = 0, R = n_len, mid, ans; 99 while(L <= R){ 100 mid = (L+R)>>1; 101 if(check(mid)){ 102 R = mid-1; 103 ans = mid; 104 } 105 else L = mid+1; 106 } 107 // cout << ans << endl; 108 string res; 109 for(int i = 0; i < N; i++){ 110 if(Rank[i] == ans){ 111 res = str.substr(i, K); 112 cout << res << endl; 113 return 0; 114 } 115 } 116 return 0; 117 }