HLJUOJ1141(数学方法或者预处理)

来源:互联网 发布:算法第四版epub下载 编辑:程序博客网 时间:2024/06/05 14:38

1141: A.Paint it!

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 12  Solved: 9
[Submit][Status][Web Board]

Description

有一个n*m的棋盘,每个格子只可能是黑和白两种颜色,你可以使用染料将某个格子染成黑色或者白色。求最少需要染多少个格子,
能使当前的棋盘变成类似于国际象棋的棋盘(每个格子临边的四个格子颜色都不与该格子的颜色相同)。

Input

n m(n,m<=100)
接下来输入n行,每行m个0/1字符

Output

最少需要染的格子数

Sample Input

2 200002 20110

Sample Output

20
解题思路:
预处理的方法用了N次,屡试不爽。但是敲起来费时间,于是找姐姐教我这类题的另一种数学解法。
对于题目要求的矩阵,无非就是两种情况:
0 1 0          1 0 1
1 0 1    或者  0 1 0
0 1 0          1 0 1
我们可以对矩阵遍历两次,以第一个符合要求矩阵为例,(i+j)的偶数位一定是0,奇数位一定是1,那么我们就记录,不符合情况总共有多少个位置;同理计算第二个有多少个不符合需要变换的位置,这样二者取最小值即可。
完整代码:
#include <functional>#include <algorithm>#include <iostream>#include <fstream>#include <sstream>#include <iomanip>#include <numeric>#include <cstring>#include <climits>#include <cassert>#include <complex>#include <cstdio>#include <string>#include <vector>#include <bitset>#include <queue>#include <stack>#include <cmath>#include <ctime>#include <list>#include <set>#include <map>using namespace std;#pragma comment(linker, "/STACK:102400000,102400000")typedef long long LL;typedef double DB;typedef unsigned uint;typedef unsigned long long uLL;/** Constant List .. **/ //{const int MOD = int(1e9)+7;const int INF = 0x3f3f3f3f;const LL INFF = 0x3f3f3f3f3f3f3f3fLL;const DB EPS = 1e-9;const DB OO = 1e20;const DB PI = acos(-1.0); //M_PI;int n , m;string str;const int maxn = 1111;int maps[maxn][maxn];int main(){    #ifdef DoubleQ    freopen("in.txt","r",stdin);    #endif    while(~scanf("%d%d",&n,&m))    {        memset(maps , 0 ,sizeof(maps));        for(int i = 0 ; i < n ; i ++)        {            cin >> str;            for(int j = 0 ; j < m ; j ++)            {                maps[i][j] = str[j] - '0';            }        }        int cnt1 = 0  , cnt2 = 0 , cnt3 = 0 , cnt4 = 0;        for(int i = 0 ; i < n ; i  ++)        {            for(int j = 0 ; j < m  ; j ++)            {                if( (i + j) % 2 == 0)                {                    if(maps[i][j] == 0)                        continue;                    else                        cnt1 ++;                }                if( (i + j) % 2 != 0)                {                    if(maps[i][j] == 1)                        continue;                    else                        cnt2 ++;                }            }        }        for(int i = 0 ; i < n ; i ++)        {            for(int j = 0 ; j < m ; j ++)            {                if( (i + j) % 2 == 0)                {                    if(maps[i][j] == 1)                        continue;                    else                        cnt3 ++;                }                if( (i + j) % 2 != 0)                {                    if(maps[i][j] == 0)                        continue;                    else                        cnt4 ++;                }            }        }        int res = min(cnt1 + cnt2 , cnt3 + cnt4);        cout << res << endl;    }}


0 0