zoukankan      html  css  js  c++  java
  • 费解的开关

    题目链接

    题意

    给出一个 5*5 的 01 矩阵, 对一个格操作可以将以该格为中心的5个格1与0变换, 求最少操作多少次可以将该矩阵全变成0。

    思路

    可以发现一个格最多点击一次, 而且可以从第一行推下去。

    枚举第一行的状态, 对每个状态进行递推, 然后判断第5行是否合法, 更新答案就可以了。

    要注意一些细节, 比如数组越界之类的。

    代码

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<vector>
    #include<map>
    #include<cmath>
    #include<cstdlib>
    #include<ctime>
    #include<queue>
    using namespace std;
    
    const int mx = 1e5 + 5;
    const int inf = 1e9;
    
    char a[7][7];
    int tmp[7][7];
    
    inline void click(int i, int j){
        tmp[i][j] ^= 1;
        tmp[i+1][j] ^= 1;
        tmp[i-1][j] ^= 1;
        tmp[i][j+1] ^= 1;
        tmp[i][j-1] ^= 1;
    }
    
    int main(){
        int t; cin >> t;
        while(t--){
            
            for(int i = 1; i <= 5; i++) scanf("%s", a[i]+1);
            
            int ans = inf, cnt = 0;
            for(int S = 0; S < (1<<5); S++){
                cnt = 0;
                for(int i = 1; i <= 5; i++){
                    for(int j = 1; j <= 5; j++) tmp[i][j] = a[i][j] - '0';
                }
                
                for(int i = 0; i < 5; i++){
                    if(S & (1<<i)) click(1, i+1), cnt++;
                }
                
                for(int i = 1; i <= 4; i++){
                    for(int j = 1; j <= 5; j++){
                        if(!tmp[i][j]) click(i+1, j), cnt++;
                    }
                }
                
                int flag = 0;
                for(int i = 1; i <= 5; i++){
                    for(int j = 1; j <= 5; j++) if(!tmp[i][j]) flag = 1;
                }
                
                if(!flag) ans = min(ans, cnt);
            }
            if(ans > 6) {
                printf("-1
    "); continue;
            }
            printf("%d
    ", ans);
        }
        
        
        return 0;
    }
  • 相关阅读:
    前端面试题六
    前端面试题五
    前端面试题四
    前端面试题之三
    前端面试题分享二
    前端面试题分享一
    JS学习笔记一
    git使用学习笔记一
    常见User-Agent
    ado.net之SQLServer和Oracle (sys_cursor) 数据库链接——获取结果集方式对比
  • 原文地址:https://www.cnblogs.com/Maktub-blog/p/11009716.html
Copyright © 2011-2022 走看看