1. 程式人生 > 實用技巧 >Codeforces Round #663 (Div. 2) D.505

Codeforces Round #663 (Div. 2) D.505

https://codeforces.ml/contest/1391/problem/D

位運算,絕妙的一個題

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>

using namespace std;

const int N = 500006;
char a[4][N];
vector<int> st;
int n,m;
vector<int> g[8];
int f[N][8];

int lowbit(int x){
    return
x & -x; } void res1(){ int ans1 = 0,ans2 = 0; for(int i = 0;i < st.size();i += 2){ if(st[i] == 0 ||st[i] == 3) ans1++; if((st[i + 1] == 1 || st[i + 1] == 2) && i + 1 < st.size()) ans1++; } for(int i = 0;i < st.size();i += 2){ if(st[i] == 1 || st[i] == 2
) ans2++; if(i + 1 < st.size() && (st[i + 1] == 0 || st[i + 1] == 3)) ans2++; } printf("%d",min(ans1,ans2)); } void res2(){ g[0] = {5,2};g[1] = {4,3}; g[2] = {7,0};g[3] = {1,6}; g[4] = {1,6};g[5] = {0,7}; g[6] = {4,3};g[7] = {5,2}; for (int i = 0; i < 8; i++) { f[
0][i] = lowbit(i ^ st[0]); } for(int i = 1;i < st.size();i++) for(int j = 0;j < 8;j++){ f[i][j] = min(f[i - 1][g[j][0]] + lowbit(j ^ st[i]), f[i - 1][g[j][1]] + lowbit(j ^ st[i])); } int ans = 0x3f3f3f3f; for(int i = 0;i < 8;i++) ans = min(ans,f[st.size() - 1][i]); printf("%d",ans); } int main(){ scanf("%d%d",&n,&m); if(n >= 4 && m >= 4){ puts("-1"); return 0; } if(n == 1||m == 1){ puts("0"); return 0; } for(int i = 0;i < n;i++) scanf("%s",a[i]); for(int i = 0;i < m;i++){ int x = 0; for(int j = 0;j < n;j++){ if(j) x <<= 1; x += a[j][i] - '0'; } st.push_back(x); } if(n == 2) res1(); else res2(); return 0; }