codeforces 1391D 状压dp

1391D 2000的题
题意:给你一个nm的矩阵(n<=m),且只包含0和1,你可以对这个矩阵进行操作,把0改为1或者把1改为0,使得这个矩阵任意xx内的1的个数为奇数,问你最少的操作次数,或者如果不行的话打印-1
思路:显然当n>=4时无解,因为4X4的矩阵是由四个2X2矩阵变化而来的 ,所以不能满足。之后就是对n=2和n=3的分类讨论,运用到状压dp的知识,我dp是真的菜
代码如下:

#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e6+10;
inline int read(){
	int x=0,f=1;char ch=getchar();
	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
	while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
	return x*f;
}
char s[maxn];
int a[4][maxn];
signed main(){
	int n = read(), m=read();
	if(n>=4){printf("-1\n"); return 0;}
	if(n==1){printf("0\n"); return 0;}
	rep(i,1,n){
		scanf("%s", s+1);
		rep(j,1,m){
			a[i][j] = s[j]-'0';
		}
	}
	if(n==2){
		int o = 0, e = 0;
		rep(i,1,m){
			int tmp = a[1][i]+a[2][i];
			if(i&1){
				if(~tmp&1) o++;
				else e++;
			}else {
				if(tmp&1) o++;
				else e++;
			}
		}
		printf("%d\n", min(o,e));
		return 0;
	}
	int ans = inf;
	rep(i,0,3){
		int tmp = 0;
		rep(j,1,m){
			int c1 = (a[1][j]+a[2][j])&1;
			int c2 = (a[2][j]+a[3][j])&1;
			int t = c1<<1|c2;
			if(j&1){
				if(i!=t) tmp++;
			}else{
				if(i+t!=3) tmp++;
			}
		}
		ans = min(tmp, ans);
	}
	printf("%d\n", ans);
	return 0;
}

你可能感兴趣的:(codeforces,DP)