kmjp's blog

競技プログラミング参加記です

Codeforces ECR #159 : E. Collapsing Strings

EFが解けたのにDで手間取りまくった回。
https://codeforces.com/contest/1902/problem/E

問題

文字列A,Bに対し、関数Cを以下のように定める。

  • AもBも空でなく、Aの末尾とBの先頭が等しいなら、C(A,B)=C(A[0:|A|-2],B[1:|B|-1])
  • そうでない場合、C(A,B)=A+B

N要素の文字列の列Sが与えられるので、それらの文字列対S[i],S[j]に対する|C(S[i],S[j])|の総和を求めよ。

解法

基本的に解は2*N*sum(|S|)であり、そこから、S[i]の末尾k文字を反転させたものとS[j]の先頭k文字が等しいなら、そこからkだけ引くことになる。
そこで、文字列を反転させた先頭k文字のハッシュ値と、それに対する頻度を取ろう。

次に、反転させない元の文字列の先頭k文字のハッシュ値を総当たりし、そのつどハッシュ値が一致する文字列の頻度の2倍を引いていけばよい。

int N;
string A[1010101];


using VT = string;

struct RollingHash {
	static const ll mo0=1000000021,mo1=1000000009;
	static ll mul0,mul1;
	static const ll add0=1000010007, add1=1003333331;
	static vector<ll> pmo[2];
	VT s; int l; vector<ll> hash_[2];
	void init(VT s) {
		this->s=s; l=s.size(); int i,j;
		hash_[0]=hash_[1]=vector<ll>(1,0);
		if(!mul0) mul0=10009+(((ll)&mul0+time(NULL))>>5)%1259,mul1=10007+(time(NULL)+((ll)&mul1)>>5)%2257;
		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);
	}
	/*以下ll版*/
	ll hash(int l,int r) { // s[l..r]
		if(l>r) return 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 (((hash_[0][r+1]+(mo0-hash_[0][l]*pmo[0][r+1-l]%mo0))%mo0)<<32) | 
			             ((hash_[1][r+1]+(mo1-hash_[1][l]*pmo[1][r+1-l]%mo1))%mo1);
	}
	ll hash(VT s) { init(s); return hash(0,s.size()-1); }
	static ll concat(ll L ,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);
		ll La=L>>32,Lb=(L<<32)>>32,Ra=R>>32,Rb=(R<<32)>>32;
		return (((Ra + La*pmo[0][RL])%mo0)<<32)|((Rb + Lb*pmo[1][RL])%mo1);
	}
};
vector<ll> RollingHash::pmo[2]; ll RollingHash::mul0,RollingHash::mul1;
RollingHash rh;
unordered_map<ll,int> H;

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N;
	ll ret=0;
	FOR(i,N) {
		cin>>A[i];
		ret+=2LL*N*A[i].size();
		s=A[i];
		reverse(ALL(s));
		rh.init(s);
		FOR(j,A[i].size()) H[rh.hash(0,j)]++;
	}
	FOR(i,N) {
		rh.init(A[i]);
		FOR(j,A[i].size()) {
			ll a=rh.hash(0,j);
			if(H.count(a)==0) break;
			ret-=2*H[rh.hash(0,j)];
		}
	}
	cout<<ret<<endl;
	
	
}

まとめ

6問回の5問目にしては易しめ。