状态压缩 洛谷P2622 非DP
初学状态压缩 对位运算不太了解
传送门
//MADE BY Y_is_sunshine;
//#include <bits/stdc++.h>
//#include <memory.h>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define INF 0x3f3f3f3f
#define MAXN 400005
const int mod = 1e9 + 7;
const double PI = acos(-1);
using namespace std;
int f[105][15];
int step[MAXN];
int N, M;
void solve() {
queue<int> q1;
char s[15];
for (int i = 0; i < N; i++)
s[i] = '1';
s[N] = '\0';
q1.push(strtol(s, NULL, 2));
step[strtol(s, NULL, 2)] = 1;
while (!q1.empty()) {
int k = q1.front();
q1.pop();
for (int i = 1; i <= M; i++) {
int temp = k;
for (int j = 1; j <= N; j++) {
if (f[i][j] == 1) {
if(temp >> (j - 1) & 1)
temp = temp ^ (1 << (j - 1));
}
else if (f[i][j] == -1) {
temp = temp | (1 << (j - 1));
}
}
if (!step[temp]) {
step[temp] = step[k] + 1, q1.push(temp);
if (!temp)
return;
}
}
}
}
int main(void)
{
freopen("data.txt", "r", stdin);
ios::sync_with_stdio(false);
//cin.tie(nullptr);
cin.tie(NULL);
cin >> N >> M;
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
cin >> f[i][j];
}
solve();
if (step[0])
cout << step[0] - 1 << endl;
else
cout << -1 << endl;
freopen("CON", "r", stdin);
system("pause");
return 0;
}

