結果

問題 No.238 Mr. K's Another Gift
ユーザー koyumeishi
提出日時 2015-07-06 18:11:23
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 83 ms / 2,000 ms
コード長 2,401 bytes
コンパイル時間 746 ms
コンパイル使用メモリ 79,408 KB
実行使用メモリ 9,984 KB
最終ジャッジ日時 2024-07-08 01:20:49
合計ジャッジ時間 3,928 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cstdio>
#include <sstream>
#include <map>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>
#include <set>
using namespace std;

class Rolling_Hash{
	void constract(const string& s){
		//hash[i] = [0,i)
		for(int i=0; i<N; i++){
			hash[i+1] = (1LL * hash[i] * P + s[i])%MOD;
		}
	}

public:
	int N;
	vector<unsigned long long> hash;
	vector<unsigned long long> p_pow;
	const unsigned long long P;
	const unsigned long long MOD;

	Rolling_Hash(const string& s, unsigned long long mod, unsigned long long p) : 
		P(p),
		MOD(mod),
		N(s.size()),
		hash(s.size()+2, 0),
		p_pow(s.size()+2)
	{
		constract(s);
		p_pow[0] = 1;
		for(int i=1; i<=N+1; i++){
			p_pow[i] = (1LL * p_pow[i-1] * P) % MOD;
		}
	}

	// [l,r)
	unsigned long long get_hash(int l, int r){
		int len = r-l;
		return (hash[r] - (1LL * hash[l]* p_pow[len])%MOD + MOD) % MOD;
	}
	unsigned long long get_mod(){
		return MOD;
	}
};

unsigned long long get_hash(Rolling_Hash& h, int i, int n){
	unsigned long long ret = h.get_hash(0,i);
	ret *= h.p_pow[n-i+1];
	ret += h.get_hash(i, n);
	ret %= h.get_mod();
	return ret;
}

unsigned long long insert_char(Rolling_Hash& h, int i, int n, int c, unsigned long long hash){
	hash += c * h.p_pow[n-i];
	hash %= h.get_mod();
	return hash;
}

#include <ctime>
int main(){
	string s;
	cin >> s;
	int n=s.size();
	string r = s;
	reverse(r.begin(), r.end());

	srand((unsigned)time(NULL));

	unsigned long long p_0 = vector<unsigned long long>{13,15,78}[rand()%3];
	unsigned long long p_1 = vector<unsigned long long>{13,15,78}[rand()%3];

	Rolling_Hash s0(s, 1000000007, p_0);
	Rolling_Hash r0(r, 1000000007, p_0);

	Rolling_Hash s1(s, 1000000009, p_1);
	Rolling_Hash r1(r, 1000000009, p_1);

	bool ok = false;
	int pos = -1;
	char c_ = '\0';
	for(int i=0; i<=n && ok==false; i++){
		auto H_s0 = get_hash(s0, i, n);
		auto H_r0 = get_hash(r0, n-i, n);

		auto H_s1 = get_hash(s1, i, n);
		auto H_r1 = get_hash(r1, n-i, n);

		for(int c='a'; c<='z'; c++){
			if(insert_char(s0, i,n,c, H_s0) != insert_char(r0, n-i,n,c, H_r0)) continue;
			if(insert_char(s1, i,n,c, H_s1) != insert_char(r1, n-i,n,c, H_r1)) continue;
			ok = true;
			pos = i;
			c_ = c;
			break;
		}

	}

	if(ok){
		string t = s.substr(0, pos);
		t += c_;
		t += s.substr(pos, string::npos);
		cout << t << endl;
	}else{
		cout << "NA" << endl;
	}


	return 0;
}
0