zoukankan      html  css  js  c++  java
  • POJ1753 Flip Game

    题目链接

    分析:

    枚举所有的操作。将每个4*4的状态用一个 int 表示, 从0 ~ 15编号。 用BFS 枚举每一种操作。

    #include <cstdio>
    #include <cmath>
    #include <iostream>
    #include <queue>
    #include <cstring>
    
    using namespace std;
    const int maxn = (1<<16);
    const int ntype = (1<<16);
    
    queue<int> Q;
    bool vis[maxn];
    int step[maxn];
    
    void init() {
        memset(vis, false, sizeof(vis));
    
        char s[5];
        int state = 0;
        for(int i=0; i<4; i++) {
            cin >>s;
            for(int j=0; j<4; j++) {
                state <<= 1;
                if(s[j] == 'w') state |= 1;
            }
        }
        Q.push(state);
        vis[state] = true;
        step[state] = 0;
    }
    
    int flip(int state, int i) {
        int nflip = 0;
        nflip |= (1<<i);
        if((i+1) % 4 != 0) nflip |= (1<<(i+1));
        if(i % 4 != 0) nflip |= (1<<(i-1));
        if((i-4) >=0) nflip |= (1<<(i-4));
        if((i+4) < 16) nflip |= (1<<(i+4));
        state ^= nflip;
        return state;
    }
    
    bool BFS() {
        while(!Q.empty()) {
            int state = Q.front(); Q.pop();
            if(state == 0 || state == (ntype-1)) {
                cout << step[state];
                return true;
            }
            for(int i=0; i<16; i++) {
                int t = flip(state, i);
                if(!vis[t]) {
                    Q.push(t);
                    vis[t] = true;
                    step[t] = step[state]+1;
                }
            }
        }
        return false;
    }
    
    int main(){
        init();
    
        if(!BFS()) cout << "Impossible\n";
    
        return 0;
    }
  • 相关阅读:
    SP338 ROADS
    [Usaco2008 Mar]牛跑步
    [Cerc2005]Knights of the Round Table
    [Poi2005]Piggy Banks小猪存钱罐
    Pku1236 Network of Schools
    PKU2186 Popular Cows 受欢迎的牛
    黑暗城堡
    入门OJ:最短路径树入门
    Sqli-labs
    Sqli-labs
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3131615.html
Copyright © 2011-2022 走看看