kmjp's blog

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

Codeforces ECR #101 : E. A Bit Similar

割とすんなり全完できた回。
https://codeforces.com/contest/1469/problem/E

問題

2つの文字列A,Bが「少し似ている」とは、A[i]=B[i]であるようなiが1個以上あることを意味する。

N文字の0/1で構成された文字列Sが与えられる。
SのうちK文字の部分文字列全パターンを考える。
いずれに対しても、「少し似ている」ようなK文字の文字列が存在するか。
存在するなら、辞書順最小値を求めよ。

解法

SのうちK文字の部分文字列全パターンのうち、先頭logN文字の組み合わせは高々O(N)通りである。
よって、先頭O(logN)文字について0/1全パターン列挙し、「1bitも一致しないものがない」ようなものを探そう。
存在するなら、辞書順最小のものを求めればよい。
先頭O(logN)文字以外は0で埋めてよい。

「1bitも一致しないものがない」ようなものがあるかの判定だが、先に0/1反転したものでローリングハッシュの集合を取っておけば、生成した文字列と一致するローリングハッシュが集合中に存在しない=どの部分文字列も1bitは一致する、ということになる。

int T,N,K;
string S;

using VT = string;

struct RollingHash {
	static const ll mo0=1000000021,mo1=1000000009;
	static ll mul0,mul1;
	static const ll add0=1000010007, add1=1003333332;
	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)%5259,mul1=10007+(((ll)&mul1)>>5)%4257;
		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);
	}
};
vector<ll> RollingHash::pmo[2]; ll RollingHash::mul0,RollingHash::mul1;

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>T;
	while(T--) {
		cin>>N>>K>>S;
		FORR(c,S) c^=1;
		
		RollingHash rh;
		rh.init(S);
		set<pair<int,int>> T;
		for(i=0;i+K<=N;i++) T.insert(rh.hash(i,i+K-1));
		
		string ret;
		FOR(i,1<<min(K,20)) {
			string R=string(K,'0');
			FOR(j,min(K,20)) if(i&(1<<j)) R[K-1-j]='1';
			rh.init(R);
			if(T.count(rh.hash(0,K-1))==0) {
				ret=R;
				break;
			}
		}
		
		if(ret.empty()) cout<<"NO"<<endl;
		else {
			cout<<"YES"<<endl;
			cout<<ret<<endl;
		}
		
	}
}

まとめ

これは思いつけて良かったね。