USACO Section 1.3: Prime Cryptarithm

好麻烦的一题

 1 /*

 2 ID: leetcod3

 3 PROG: crypt1

 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 <cstdlib>

17 #include <limits>

18 #include <stack>

19 

20 using namespace std;

21 

22 ofstream fout ("crypt1.out");

23 ifstream fin ("crypt1.in");

24 

25 void uphelp(vector<int> &up, vector<int> &num, int dep, int ult, int cur) {

26     if (dep == ult) {

27         up.push_back(cur);

28         return;

29     }

30     for (int i = 0; i < num.size(); i++) {

31         uphelp(up, num, dep+1, ult, cur*10 + num[i]);

32     }

33 }

34 

35 bool checkhelp(int n, set<int> &save) {

36     while (n) {

37         int tmp = n % 10;

38         if (save.find(tmp) == save.end()) return false;

39         n /= 10;

40     }

41     return true;

42 }

43 

44 bool check(int up, int down, set<int> &save) {

45     int tmp = up * down;

46     if (!checkhelp(tmp, save)) return false;

47     if (up * down >= 10000 || up * down <= 999) return false;

48     while (down) {

49         int tmp = down % 10;

50         if (tmp * up >= 1000 || tmp * up <= 99 || !checkhelp(tmp*up, save)) return false;

51         down /= 10;

52     }

53     return true;

54 }

55 

56 int main() {

57     int N;

58     fin >> N;

59     vector<int> num(N);

60     set<int> save;

61     for (int i = 0; i < N; i++) {

62         fin >> num[i];

63         save.insert(num[i]);

64     }

65     int ans = 0;

66     vector<int> up;

67     vector<int> down;

68     uphelp(up, num, 0, 3, 0);

69     uphelp(down, num, 0, 2, 0);

70     for (int i = 0; i < up.size(); i++) {

71         for (int j = 0; j < down.size(); j++) {

72             if (check(up[i], down[j], save)) ans++;

73         }

74     }

75     fout << ans << endl;

76 

77     return 0;

78 }

 

你可能感兴趣的:(USACO)