这题有个小技巧, 按一个键两次等于没按,所以如果depsum > 16的话其实不用做深搜到depsum次,而只要16次就可以了。
1 /* 2 ID: yingzho1 3 LANG: C++ 4 TASK: lamps 5 */ 6 #include <iostream> 7 #include <fstream> 8 #include <string> 9 #include <map> 10 #include <vector> 11 #include <set> 12 #include <algorithm> 13 #include <stdio.h> 14 #include <queue> 15 #include <cstring> 16 17 using namespace std; 18 19 ifstream fin("lamps.in"); 20 ofstream fout("lamps.out"); 21 22 int N, depsum; 23 24 bool check(string s, vector<int> &on, vector<int> &off) { 25 for (int i = 0; i < on.size(); i++) { 26 if (s[on[i]] != '1') return false; 27 } 28 for (int i = 0; i < off.size(); i++) { 29 if (s[off[i]] != '0') return false; 30 } 31 return s.size(); 32 } 33 34 void dfs(set<string> &res, int c1, int c2, int c3, int c4, string s, vector<int> &on, vector<int> &off, int dep) { 35 if (check(s, on, off)) { 36 if (dep <= depsum && (depsum-dep)%2 == 0) { 37 res.insert(s); 38 //return; 39 } 40 } 41 if (dep == 4 || dep > depsum) return; 42 string pre = s; 43 if (c1 < 1) { 44 dfs(res, c1+1, c2, c3, c4, s, on, off, dep+1); 45 for (int i = 0; i < s.size(); i++) { 46 if (s[i] == '0') s[i] = '1'; 47 else s[i] = '0'; 48 } 49 dfs(res, c1+1, c2, c3, c4, s, on, off, dep+1); 50 } 51 52 s = pre; 53 54 if (c2 < 1) { 55 dfs(res, c1, c2+1, c3, c4, s, on, off, dep+1); 56 for (int i = 0; i < s.size(); i++) { 57 if (i % 2 == 1) { 58 if (s[i] == '1') s[i] = '0'; 59 else s[i] = '1'; 60 } 61 } 62 dfs(res, c1, c2+1, c3, c4, s, on, off, dep+1); 63 } 64 65 s = pre; 66 if (c3 < 1) { 67 dfs(res, c1, c2, c3+1, c4, s, on, off, dep+1); 68 for (int i = 0; i < s.size(); i++) { 69 if (i % 2 == 0) { 70 if (s[i] == '1') s[i] = '0'; 71 else s[i] = '1'; 72 } 73 } 74 dfs(res, c1, c2, c3+1, c4, s, on, off, dep+1); 75 } 76 77 s = pre; 78 if (c4 < 1) { 79 dfs(res, c1, c2, c3, c4+1, s, on, off, dep+1); 80 for (int i = 0; i < s.size(); i++) { 81 if (i % 3 == 0) { 82 if (s[i] == '1') s[i] = '0'; 83 else s[i] = '1'; 84 } 85 } 86 dfs(res, c1, c2, c3, c4+1, s, on, off, dep+1); 87 } 88 89 s = pre; 90 } 91 92 int main() 93 { 94 fin >> N >> depsum; 95 string s(N, '1'); 96 int n; 97 vector<int> on, off; 98 //cout << N << " " << depsum << endl; 99 while (fin >> n && n != -1) on.push_back(n-1); 100 while (fin >> n && n != -1) off.push_back(n-1); 101 //for (int i = 0; i < on.size(); i++) cout << on[i] << endl; 102 //for (int i = 0; i < off.size(); i++) cout << off[i] << endl; 103 set<string> res; 104 dfs(res, 0, 0, 0, 0, s, on, off, 0); 105 vector<string> ret; 106 for (set<string>::iterator it = res.begin(); it != res.end(); it++) ret.push_back(*it); 107 sort(ret.begin(), ret.end()); 108 if (ret.size() == 0) { 109 fout << "IMPOSSIBLE" << endl; 110 return 0; 111 } 112 for (int i = 0; i < ret.size(); i++) { 113 fout << ret[i] << endl; 114 } 115 116 return 0; 117 }