B.Connect3 2017-2018 ACM-ICPC, Asia Daejeon Regional Contest 状压+回溯

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ujn20161222/article/details/82940285

Connect3 is a simplified version of a well-known Connect4 game. Connect3 is a game for two players, black and white, who take turns placing their colored stones in a 4 x 4 grid board shown in Fig.B.1. Each square (or box) in the grid is represented by a pair of numbers (a, b) where a is for a row and b is for a column. The lower left corner of the board is (1, 1), and the upper right corner is (4, 4). Each player selects a column to place a stone which is then placed on the lowest empty square in the column. For example, square (3, 1) is to be taken only when squares (2, 1) and (1, 1) are occupied beforehand. The game ends if three stones with the same color connect in either horizontally, diagonally, or vertically in a row and the player of the color wins.

The game starts by a player placing a black stone on square (1, x). If the game ends by the white player placing a stone on square (a, b), let the final state of the board be s. You are to write a program to find the number of all possible unique states of s. Note that the order of stones placed is irrelevant.

输入

Your program is to read from standard input. The input starts with a line containing an integer x (1 ≤ x ≤ 4), representing the column of the first stone placed on the board. The next line of input shows two integers, a and b for square (a, b) which is the position of the last stone placed on the board.

输出

Your program is to write to standard output. Print exactly one number that corresponds to the answer.

样例输入

2
2 3

样例输出

516
#include<bits/stdc++.h> 

using namespace std;

const int dx[4]={1,0,1,1};
const int dy[4]={1,1,-1,0};

int a[6][6];
int px,py,ans;

bool check(int x,int y){
	int t=a[x][y];
	for(int i=0;i<4;i++){
		int s=0;
		for(int nx=x,ny=y;a[nx][ny]==t;nx+=dx[i],ny+=dy[i])s++;
		for(int nx=x,ny=y;a[nx][ny]==t;nx-=dx[i],ny-=dy[i])s++;
		if(s-1>=3)return true;
	}
	return false;
}

int encode(){
	int c=0;
	for(int i=1;i<=4;i++)
	for(int j=1;j<=4;j++)
	c=c*3+a[i][j];
	return c;
}

set<int> vis;

void dfs(int t){
	for(int j=1;j<=4;j++){
		int i=1;
		while(a[i][j])i++;
		if(i>4)continue;
		a[i][j]=t;
		int c=encode();
		if(vis.count(c)){
			a[i][j]=0;
			continue;
		}
		if(check(i,j)){
			if(t==2&&px==i&&py==j)ans++;
			a[i][j]=0;
			continue;
		}
		vis.insert(c);
		dfs(3-t);
		a[i][j]=0; 
	}
}


int main(){
	int x;
	scanf("%d%d%d",&x,&px,&py);
	a[1][x]=1;
	dfs(2);
	printf("%d\n",ans);
	return 0;
}




猜你喜欢

转载自blog.csdn.net/ujn20161222/article/details/82940285