/* ID: lucien23 PROG: lamps LANG: C++ */ /* * 此题的技巧之处就是需要注意到任何button只要按下2的倍数次就相当于没有按 * 所以其实只需要考虑4个按钮,每个按钮是否被有效按下过一次就好 * 直接使用枚举法,一共只有2^4=16种情况 * 对于每种情况需要知道被按下的有效次数(也就是被按下过的按钮数),必须满足 * (C-有效次数)%2=0才行,这样其他次数才能视为无效 * 然后验证各种情况是否符合要求,将符合要求的情况按序输出即可 */ #include <iostream> #include <fstream> #include <vector> #include <algorithm> using namespace std; bool compPro(int *strNum1, int *strNum2) { int i = 0; while (1) { if (strNum1[i] < strNum2[i]) return true; else if (strNum1[i] > strNum2[i]) return false; i++; } } int main() { ifstream infile("lamps.in"); ofstream outfile("lamps.out"); if(!infile || !outfile) { cout << "file operation failure!" << endl; return -1; } int N, C; vector<int> vecOnLamps, vecOffLamps; vector<int*> results; infile >> N >> C; int num; infile >> num; while (num != -1) { vecOnLamps.push_back(num); infile >> num; } infile >> num; while (num != -1) { vecOffLamps.push_back(num); infile >> num; } int count = 0; for (int i=0; i<16; i++) { int *lamps = new int[N]; for (int j=0; j<N; j++) { lamps[j] = 1; } int tempCnt = 0; for (int j=0; j<4; j++) { int temp = 1 << j; if ((temp & i) == temp) tempCnt++; } if (C < tempCnt || (C - tempCnt) % 2 != 0) { delete[] lamps; continue; } if (((1 << 0) & i) == (1 << 0)) { for (int j=0; j<N; j++) { if (lamps[j] == 0) lamps[j] = 1; else lamps[j] = 0; } } if (((1 << 1) & i) == (1 << 1)) { for (int j=0; j<N; j++) { if ((j+1)%2 == 1) { if (lamps[j] == 0) lamps[j] = 1; else lamps[j] = 0; } } } if (((1 << 2) & i) == (1 << 2)) { for (int j=0; j<N; j++) { if ((j+1)%2 == 0) { if (lamps[j] == 0) lamps[j] = 1; else lamps[j] = 0; } } } if (((1 << 3) & i) == (1 << 3)) { for (int j=0; j<N; j++) { if ((j+1)%3 == 1) { if (lamps[j] == 0) lamps[j] = 1; else lamps[j] = 0; } } } bool flag = true; for (vector<int>::iterator it=vecOnLamps.begin(); it!=vecOnLamps.end(); it++) { if (lamps[*it-1] != 1) { flag = false; break; } } if (!flag) { delete[] lamps; continue; } for (vector<int>::iterator it=vecOffLamps.begin(); it!=vecOffLamps.end(); it++) { if (lamps[*it-1] != 0) { flag = false; break; } } if (flag) { count++; results.push_back(lamps); } else { delete[] lamps; } } if (count == 0) { outfile << "IMPOSSIBLE" << endl; } else { sort(results.begin(), results.end(), compPro); for (int i=0; i<count; i++) { for (int j=0; j<N; j++) { outfile << results[i][j]; } outfile << endl; } } return 0; }
USACO Section 2.2 Party Lamps,布布扣,bubuko.com
原文地址:http://blog.csdn.net/lucienduan/article/details/38369825