なんとか全完できてよかった。
https://www.hackerrank.com/contests/101hack50/challenges/cutting-the-string
問題
文字列Sが与えられる。
Sから空でない連続した部分文字列を抜きだして、前後の文字を隙間なく連結し、抜き出したものをまたSのどこかに挿入することを考える。
処理の前後で文字列が変化しないような抜出・挿入位置の組み合わせを求めよ。
解法
文字列が変化しない条件を考える。
部分文字列S[L..R]が、最小周期Pの文字列TをQ回繰り返したものだとする。
この場合、この範囲でPの倍数の長さ、すなわちT何個か分を抜き出してまたもともとS[L..R]だった範囲のいずれかに戻すと元の形に戻せる。
Tをi回繰り返したものを抜き出す位置は(Q+1-i)通り、戻す位置は(Q+1-i)通りなので、可能な組み合わせはとなる。
S[L..R]について処理した場合、その部分文字列のうちTを繰り返したものは多重でカウントする必要はない。
周期性のチェックはRollingHash等使えば全体でO(|S|^2)で処理できる。
struct RollingHash { static const ll mo0=1000000007,mo1=1000000009; static ll mul0,mul1; static const ll add0=1000010007, add1=1003333331; static vector<ll> pmo[2]; string s; int l; vector<ll> hash_[2]; void init(string s) { this->s=s; l=s.size(); int i,j; hash_[0]=hash_[1]=vector<ll>(1,0); if(!mul0) mul0=10009+(((ll)&mul0)>>5)%259,mul1=10007+(((ll)&mul1)>>5)%257; if(pmo[0].empty()) pmo[0].push_back(1),pmo[1].push_back(1); FOR(i,l) hash_[0].push_back((hash_[0].back()*mul0+add0+s[i])%mo0); FOR(i,l) hash_[1].push_back((hash_[1].back()*mul1+add1+s[i])%mo1); } pair<ll,ll> hash(int l,int r) { // s[l..r] if(l>r) return make_pair(0,0); while(pmo[0].size()<r+2) pmo[0].push_back(pmo[0].back()*mul0%mo0), pmo[1].push_back(pmo[1].back()*mul1%mo1); return make_pair((hash_[0][r+1]+(mo0-hash_[0][l]*pmo[0][r+1-l]%mo0))%mo0, (hash_[1][r+1]+(mo1-hash_[1][l]*pmo[1][r+1-l]%mo1))%mo1); } pair<ll,ll> hash(string s) { init(s); return hash(0,s.size()-1); } static pair<ll,ll> concat(pair<ll,ll> L,pair<ll,ll> R,int RL) { // hash(L+R) RL=len-of-R while(pmo[0].size()<RL+2) pmo[0].push_back(pmo[0].back()*mul0%mo0), pmo[1].push_back(pmo[1].back()*mul1%mo1); return make_pair((R.first + L.first*pmo[0][RL])%mo0,(R.second + L.second*pmo[1][RL])%mo1); } }; vector<ll> RollingHash::pmo[2]; ll RollingHash::mul0,RollingHash::mul1; int N; string S; ll ret=0; RollingHash rh; int did[6060][6060]; void solve() { int i,j,k,l,r,x,y; string s; cin>>S; N=S.size(); rh.init(S); FOR(x,N) { for(y=1;x+y<=N;y++) if(did[x][y]==0) { int z; for(z=1;z<=N;z++) { if(x+z*y>N) break; if(rh.hash(x,x+y-1)!=rh.hash(x+y*z,x+y*(z+1)-1)) break; } for(j=x;j<=x+y*(z-1);j+=y) { for(k=y;j+k<=x+(y*z);k+=y) { did[j][k]=1; } } ret += 1LL*z*(z+1)*(2*z+1)/6; } } cout<<ret<<endl; }
まとめ
一発で通るとは思わなかった。