练习赛补题------B Connect3 dfs模拟

题目:https://codeforces.com/gym/101667/attachments

难点只是在如何标记出现过的状态,这样相当于剪枝了,只有三种状态,所以可以用三进制来编码16个数字得到一个唯一的数;
剩下的就是很普通的搜索了

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
#define mp make_pair
#define pb push_back
#define fi first
#define se second

int line[10];
map<LL,int>mk;
int mm[10][10];
int a,b;

LL haxi()
{
    LL sum = 0;
    for(int i = 0;i < 4;++i){
        for(int j = 0;j < 4;++j){
            sum = sum * 3 + mm[i][j];
        }
    }
    return sum;
}

bool judge(int x)
{
    for(int i = 0;i < 4;++i){
        for(int j = 0;j < 4;++j){
            if(i + 2 <= 3){
                if(mm[i][j] == mm[i + 1][j] && mm[i][j] == mm[i + 2][j] && x == mm[i][j]){
                    return true;
                }
            }
            if(j + 2 <= 3){
                if(mm[i][j] == mm[i][j + 1] && mm[i][j] == mm[i][j + 2] && x == mm[i][j]){
                    return true;
                }
            }
            if(i + 2 <= 3 && j + 2 <= 3){
                if(mm[i][j] == mm[i + 1][j + 1] && mm[i][j] == mm[i + 2][j + 2] && x == mm[i][j]){
                    return true;
                }
            }
            if(i - 2 >= 0 && j + 2 <= 3){
                if(mm[i][j] == mm[i - 1][j + 1] && mm[i][j] == mm[i - 2][j + 2] && x == mm[i][j]){
                    return true;
                }
            }
        }
    }
    return false;
}

int ans = 0;
void dfs(int step)
{
    LL x = haxi();
    if(mk[x] == 1) return ;
    mk[x] = 1;
    if(judge(1) || judge(2) || mm[a][b] != 0){
        //这三种情况需要返回,白棋连成线,黑棋连成线
        if(judge(2) && mm[a][b] == 2){
            ++ans;
        }
        return ;
    }
    for(int i = 0;i < 4;++i){
        if(line[i] == 4){
            continue;
        }
        int tmp = step % 2;
        if(tmp == 0) tmp = 2;
        mm[i][line[i]] = tmp;
        line[i]++;
        dfs(step + 1);
        line[i]--;
        mm[i][line[i]] = 0;
    }
    return ;
}

int main()
{
    int x;
    scanf("%d",&x);
    scanf("%d %d",&b,&a);
    a--;b--;
    memset(mm,0,sizeof(mm));
    memset(line,0,sizeof(line));
    mm[x - 1][0] = 1;
    line[x - 1]++;
    ans = 0;
    dfs(0);
    printf("%d\n",ans);
    return 0;
}

发布了269 篇原创文章 · 获赞 33 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36386435/article/details/89047354