1. 程式人生 > >【dfs套dfs套dfs】算24點

【dfs套dfs套dfs】算24點

 Luogu P1236 算24點

值得紀念一下

  1 #include<cstdio>
  2 #include<iostream>
  3 #define ri register int
  4 #define ll long long
  5 using namespace std;
  6 int a, b, c, d;
  7 int ans[20];
  8 char s[5];
  9 bool flag = 0;
 10 bool dfs3(int x, int y) {
 11     if(x < y) swap(x, y);
12 if(x + y == 24) { 13 ans[1] = x, ans[2] = y; 14 s[1] = '+'; 15 return true; 16 } 17 else if(x - y == 24) { 18 ans[1] = x, ans[2] = y; 19 s[1] = '-'; 20 return true; 21 } 22 else if(x * y == 24) { 23 ans[1
] = x, ans[2] = y; 24 s[1] = '*'; 25 return true; 26 } 27 else if(y) { 28 if(x % y == 0) { 29 if(x / y == 24) { 30 ans[1] = x, ans[2] = y; 31 s[1] = '/'; 32 return true; 33 } 34 }
35 } 36 return false; 37 } 38 bool dfs2(int x, int y, int z) { 39 if(x < y) swap(x, y); 40 if(dfs3(x+y, z)) { 41 ans[3] = x, ans[4] = y, ans[11] = x+y; 42 s[2] = '+'; 43 return true; 44 } 45 if(dfs3(x-y, z)) { 46 ans[3] = x, ans[4] = y, ans[11] = x-y; 47 s[2] = '-'; 48 return true; 49 } 50 if(dfs3(x*y, z)) { 51 ans[3] = x, ans[4] = y, ans[11] = x*y; 52 s[2] = '*'; 53 return true; 54 } 55 if(y) { 56 if(x % y == 0) { 57 if(dfs3(x/y, z)) { 58 ans[3] = x, ans[4] = y, ans[11] = x/y; 59 s[2] = '/'; 60 return true; 61 } 62 } 63 } 64 return false; 65 } 66 bool dfs1(int x, int y, int n, int m) { 67 if(x < y) swap(x, y); 68 if(dfs2(x+y, n, m)) { 69 ans[5] = x, ans[6] = y, ans[10] = x+y; 70 s[3] = '+'; 71 return true; 72 } 73 if(dfs2(x-y, n, m)) { 74 ans[5] = x, ans[6] = y, ans[10] = x-y; 75 s[3] = '-'; 76 return true; 77 } 78 if(dfs2(x*y, n, m)) { 79 ans[5] = x, ans[6] = y, ans[10] = x*y; 80 s[3] = '*'; 81 return true; 82 } 83 if(y) { 84 if(x % y == 0) { 85 if(dfs2(x/y, n, m)) { 86 ans[5] = x, ans[6] = y, ans[10] = x/y; 87 s[3] = '/'; 88 return true; 89 } 90 } 91 } 92 return false; 93 } 94 void print() { 95 cout<<ans[5]<<s[3]<<ans[6]<<"="<<ans[10]<<endl; 96 cout<<ans[3]<<s[2]<<ans[4]<<"="<<ans[11]<<endl; 97 cout<<ans[1]<<s[1]<<ans[2]<<"=24"; 98 } 99 int main() { 100 scanf("%d%d%d%d", &a, &b, &c, &d); 101 if(dfs1(a, b, c, d)) { 102 flag = 1; 103 print(); 104 return 0; 105 } 106 if(dfs1(a, c, b, d)) { 107 flag = 1; 108 print(); 109 return 0; 110 } 111 if(dfs1(a, d, b, c)) { 112 flag = 1; 113 print(); 114 return 0; 115 } 116 if(dfs1(b, c, a, d)) { 117 flag = 1; 118 print(); 119 return 0; 120 } 121 if(dfs1(b, d, a, c)) { 122 flag = 1; 123 print(); 124 return 0; 125 } 126 if(dfs1(c, d, a, b)) { 127 flag = 1; 128 print(); 129 return 0; 130 } 131 if(!flag) printf("No answer!"); 132 return 0; 133 }

但資料‘1 3 5 7’過不了qwq

但luogu資料水我能過qwq