您的位置:首页 > 其它

USACO 1.4 Prime Palindromes

2015-01-24 00:18 405 查看
构造所有回文再判断。 时间不完美。

Executing...
Test 1: TEST OK [0.024 secs, 3504 KB]
Test 2: TEST OK [0.027 secs, 3504 KB]
Test 3: TEST OK [0.027 secs, 3504 KB]
Test 4: TEST OK [0.024 secs, 3504 KB]
Test 5: TEST OK [0.024 secs, 3504 KB]
Test 6: TEST OK [0.024 secs, 3504 KB]
Test 7: TEST OK [0.057 secs, 3504 KB]
Test 8: TEST OK [0.065 secs, 3504 KB]
Test 9: TEST OK [0.059 secs, 3504 KB]

/*
TASK:pprime
LANG:C++
*/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <algorithm>
using namespace std;

int a[12];
int Q[800] = {0, 11, 0x7fffffff},tail=2;

void check(int t)
{
int tmp = 0;
for (int i = 1; i <= t; ++ i) tmp = tmp * 10 + a[i];
for (int j = 2; j <= sqrt(tmp); ++ j)
if (!(tmp % j)) return;
Q[++tail] = tmp;
}

void init()
{
int tmp, t, j;
for (int i = tmp = 3; i != 10000; tmp = ++ i)
{
t = 0;
while (tmp)
{
a[++t] = tmp % 10;
tmp /= 10;
}
if (!(a[t]&1)) continue;
for (j = 1; j <= t / 2; ++ j) swap(a[j],a[t - j + 1]);
for (j = 1; j < t; ++ j) a[t + j] = a[t - j];
check(t * 2 - 1);
for (j = 1; j <= t; ++ j) a[t + j] = a[t - j + 1];
check(t * 2);
}
sort(Q + 1, Q + 1 + tail);
}

int main()
{
freopen("pprime.in","r", stdin);
freopen("pprime.out", "w", stdout);
ios::sync_with_stdio(false);
init();
int L, R;
cin >> L >> R;
for (int i = 1; ; ++ i)
if(Q[i]>=L)
{
L = i;
break;
}
cout<<Q[L]<<endl;
while (Q[L + 1] <= R) cout<<Q[++L]<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: