結果
| 問題 | No.12 限定された素数 | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2015-01-20 14:37:55 | 
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 87 ms / 5,000 ms | 
| コード長 | 1,420 bytes | 
| コンパイル時間 | 697 ms | 
| コンパイル使用メモリ | 72,924 KB | 
| 実行使用メモリ | 6,064 KB | 
| 最終ジャッジ日時 | 2024-11-24 07:39:18 | 
| 合計ジャッジ時間 | 2,884 ms | 
| ジャッジサーバーID (参考情報) | judge2 / judge5 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 26 | 
ソースコード
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <utility>
#include <set>
using namespace std;
int main() {
	const int limit = 5000000;
	int n;
	cin >> n;
	bool selected[10] = {};
	for (int i = 0; i < n; i++) {
		int a;
		cin >> a;;
		selected[a] = true;
	}
	vector<bool> isPrime(limit + 1, true);
	isPrime[0] = isPrime[1] = false;
	for (int i = 2; i * i <= limit; i++) {
		if (isPrime[i]) {
			for (int j = 2 * i; j <= limit; j += i) {
				isPrime[j] = false;
			}
		}
	};
	// 0, limit + 1 は素数ではないが、計算を楽にするために挿入
	vector<int> primes;
	primes.push_back(0);
	for (int i = 0; i <= limit; i++) {
		if (isPrime[i]) {
			primes.push_back(i);
		}
	}
	primes.push_back(limit+1);
	int np = primes.size();
	set<int> check;
	int ans = -1;
	int start = -1;
	// i = 0, np - 1は計算を楽にするために挿入しただけなので除く
	for (int i = 1; i < np - 1; i++) {
		int tmp = primes[i];
		bool ok = true;
		while (tmp > 0) {
			int digit = tmp % 10;
			if (!selected[digit]) {
				ok = false;
				break;
			}
			tmp /= 10;
		}
		if (!ok) {
			check.clear();
			continue;
		}
		if (check.size() == 0) {
			start = i;
		}
		tmp = primes[i];
		while (tmp > 0) {
			check.insert(tmp % 10);
			tmp /= 10;
		}
		if (check.size() == n) {
			ans = max(ans, primes[i + 1] - primes[start - 1] - 2);
		}
	}
	cout << ans << endl;
	return 0;
}
            
            
            
        