結果

問題 No.12 限定された素数
ユーザー masamasa
提出日時 2015-01-20 14:37:55
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 79 ms / 5,000 ms
コード長 1,420 bytes
コンパイル時間 685 ms
コンパイル使用メモリ 74,060 KB
実行使用メモリ 6,020 KB
最終ジャッジ日時 2023-08-15 22:31:44
合計ジャッジ時間 3,055 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 34 ms
5,856 KB
testcase_01 AC 40 ms
5,800 KB
testcase_02 AC 36 ms
5,744 KB
testcase_03 AC 73 ms
5,736 KB
testcase_04 AC 40 ms
5,792 KB
testcase_05 AC 46 ms
5,872 KB
testcase_06 AC 51 ms
5,800 KB
testcase_07 AC 60 ms
5,688 KB
testcase_08 AC 45 ms
5,856 KB
testcase_09 AC 43 ms
5,864 KB
testcase_10 AC 42 ms
5,684 KB
testcase_11 AC 79 ms
5,856 KB
testcase_12 AC 61 ms
5,788 KB
testcase_13 AC 49 ms
5,860 KB
testcase_14 AC 42 ms
5,688 KB
testcase_15 AC 48 ms
5,688 KB
testcase_16 AC 69 ms
5,908 KB
testcase_17 AC 35 ms
5,688 KB
testcase_18 AC 34 ms
5,736 KB
testcase_19 AC 36 ms
5,880 KB
testcase_20 AC 39 ms
6,020 KB
testcase_21 AC 40 ms
5,860 KB
testcase_22 AC 35 ms
5,824 KB
testcase_23 AC 36 ms
5,736 KB
testcase_24 AC 35 ms
5,736 KB
testcase_25 AC 43 ms
5,736 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#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;
}
0