kmjp's blog

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

LeetCode Weekly Contest 146 : 1147. Longest Chunked Palindrome Decomposition

色々運営がグダった回。
https://leetcode.com/contest/weekly-contest-148/problems/longest-chunked-palindrome-decomposition/

問題

N文字の文字列Sが与えられる。
これらをいくつかの部分列の連結となるよう分解したい。
その際、前からi個目の部分列と後ろからi個目の部分列が一致するような分解のうち、もっとも数多くの部分列の連結となるのは何個か。

解法

f(n) := Sの先頭からn文字と末尾からn文字を除いた部分文字列に対し、問題文の条件を満たす最大の部分列連結数
とすると、Sの先頭(n+1)文字目~n+m文字目と、Sの末尾n+m文字目~(n+1)文字目が一致するならf(n) = 2+f(n+m)となるので、mを総当たりすればよい。
文字列の一致判定をローリングハッシュでO(1)でできるなら状態がO(N)、遷移がO(N)でO(N^2)で間に合う。

int N;
int memo[1002];

ll mul0,mul1;
vector<ll> pmo[2];
ll mo0=1000000021,mo1=1000000009;
ll add0=1000010007, add1=1003333331;

struct RollingHash {
	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);
	}
};



RollingHash rh;

class Solution {
public:
	int hoge(int L,int R) {
		if(L==R) return 0;
		if(L+1==R) return 1;
		if(memo[L]>=0) return memo[L];
		int ret=1;
		for(int x=1;L+2*x<=R;x++) {
			if(rh.hash(L,L+x-1)==rh.hash(R-x,R-1)) {
				ret=max(ret,2+hoge(L+x,R-x));
			}
		}
		return memo[L]=ret;
		
		
	}
    int longestDecomposition(string text) {
		rh.init(text);
        MINUS(memo);
        return hoge(0,text.size());
        
    }
};

まとめ

これ7ptで良くない?