首页 > 代码库 > USACO Section 2.1: Hamming Codes

USACO Section 2.1: Hamming Codes

dfs简单题

 1 /* 2 ID: yingzho2 3 PROG: hamming  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 ("hamming.out");24 ifstream fin ("hamming.in");25 26 int N, B, D;27 28 bool check(int x, vector<int> &ans) {29     for (int i = 0; i < ans.size(); ++i) {30         int num = 0;31         for (int j = 0; j < B; ++j) {32             if (((x >> j) & 1) != ((ans[i] >> j) & 1)) num++;33         }34         if (num < D) return false;35     }36     return true;37 }38 39 40 void find(vector<int> &ans) {41     if (ans.size() == N) return;42     int x = ans[ans.size()-1] + 1;43     while(ans.size() < N) {44         if (check(x, ans)) {45             ans.push_back(x);46             find(ans);47         }48         else x++;49     }50 }51 52 int main()53 {54     fin >> N >> B >> D;55     vector<int> ans;56     ans.push_back(0);57     find(ans);58     int num = 0;59     while (num < N-1) {60         fout << ans[num];61         if (num % 10 == 9) fout << endl;62         else fout << " ";63         num++;64     }65     fout << ans[N-1] << endl;66     return 0;67 }

 

USACO Section 2.1: Hamming Codes