USACO Section 1.5: Prime Palindromes

这题的关键点:

1.不能检查是否palindrome,否则会TLE

2.检查Prime上限一定为sqrt(x)。

 1 /*

 2 ID: leetcod3

 3 PROG: pprime

 4 LANG: C++

 5 */

 6 #include <iostream>

 7 #include <fstream>

 8 #include <string>

 9 #include <map>

10 #include <vector>

11 #include <set>

12 #include <algorithm>

13 #include <queue>

14 #include <cmath>

15 #include <list>

16 #include <cstring>

17 #include <cstdlib>

18 #include <limits>

19 #include <stack>

20 

21 using namespace std;

22 

23 ofstream fout ("pprime.out");

24 ifstream fin ("pprime.in");

25 

26 vector<int> S;

27 

28 bool prime(int x) {

29     int root = (int)sqrt(x*1.0);

30     for (int i = 2; i <= root; i++) {

31         if (x % i == 0) return false;

32     }

33     return true;

34 }

35 

36 void dfs(int x, int len) {

37     if (len > 8) return;

38     int factor = 1;

39     if (prime(x)) S.push_back(x);

40     for (int i = 0; i < len; ++i) factor *= 10;

41     for (int i = 0; i < 10; ++i) {

42         int tmp = factor * i;

43         tmp += x;

44         tmp *= 10;

45         tmp += i;

46         dfs(tmp, len+2);

47     }

48 }

49 

50 int main()

51 {

52     int a, b;

53     fin >> a >> b;

54     for (int i = 0; i < 10; i++) dfs(i, 1);

55     S.push_back(11);

56     sort(S.begin(), S.end());

57     for (int i = 0; i < S.size(); i++) {

58         if (S[i] < a) continue;

59         if (S[i] > b) break;

60         fout << S[i] << endl;

61     }

62     /*for (set<int>::iterator it = S.begin(); it != S.end(); it++) {

63         if (*it < a) continue;

64         if (*it > b) break;

65         fout << *it << endl;

66     }*/

67     return 0;

68 }

 

你可能感兴趣的:(USACO)