kmjp's blog

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

CSAcademy Round #20 : E. Palindromic Concatenation

こっちの方がだいぶすんなり解けた。
https://csacademy.com/contest/round-20/#task/palindromic-concatenation

問題

N個の文字列S[i]が与えられる。
i!=jかつS[i]+S[j]が回文となるような(i,j)の対の数を求めよ。

解法

S[i] = S[j] のケースを先に片づける。

S[i]を反転したものをmapに放り込んでおけば、S[j]と連結して回文を作れるS[i]の数は容易に求められる。

あとは|S[i]|!=|S[j]|のケースを考える。
2つの文字列を連結したA+Bが回文になる場合、ある文字列Xとその反転文字列X'、および回文Yを用いてA=X'+Y,B=XまたはA=X,B=Y+X'の形を取る。
よって、文字を長い順に処理し、S[i]のprefixまたはsuffixが回文となってS[i]=Y+X'またはS[i]=X'+Yの形で表せる場合、以降S[j]=Xが登場したら連結して回文を生成できるので、X'をmapに登録して数え上げていこう。

とはいえX'を逐一mapに入れるとMLEするので、ハッシュ値を使うのが良い。
prefix/suffixの回文判定も、S[i]およびS[i]の反転文字列のハッシュ値を使えば高速に行える。
Trie+Manacherでも解けるようだ。

int N;
vector<string> S[101010];
ll ret;

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); }
};
vector<ll> RollingHash::pmo[2]; ll RollingHash::mul0,RollingHash::mul1;

map<ll,int> cand[101010];

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N;
	FOR(i,N) {
		cin>>s;
		S[s.size()].push_back(s);
	}
	
	// samelen
	FOR(i,101000) {
		map<string,int> M;
		FORR(e,S[i]) {
			ret += 2*M[e];
			s=e;
			reverse(ALL(s));
			M[s]++;
		}
	}
	for(i=101000;i>=1;i--) {
		FORR(e,S[i]) {
			RollingHash rh;
			auto ha = rh.hash(e);
			ret += cand[i][(ha.first<<32)+ha.second];
		}
		FORR(e,S[i]) {
			string r=e;
			reverse(ALL(r));
			RollingHash rh,rhr;
			rh.init(e);
			rhr.init(r);
			for(x=1;x<i;x++) {
				// tail
				if(rh.hash(i-x,i-1)==rhr.hash(0,x-1)) {
					auto h=rhr.hash(x,i-1);
					cand[i-x][(h.first<<32)+h.second]++;
				}
				// head
				if(rhr.hash(i-x,i-1)==rh.hash(0,x-1)) {
					auto h=rhr.hash(0,i-x-1);
					cand[i-x][(h.first<<32)+h.second]++;
				}
			}
		}
	}
	cout<<ret<<endl;
}

まとめ

これはすんなり方針が思いつけてよかった。