洛谷P2346 四子连棋

IDDFS+哈希判重

代码怎么这么长

#include<iostream>
#include<cstring>
using namespace std;
int G[4][4],ax,ay,bx,by;
int have[4100000]={0},k;
bool hash[4100000]={0},ok=0;
const int mx[4]={1,-1,0,0};
const int my[4]={0,0,1,-1};
bool equ(int a,int b,int c,int d);
inline bool check(void);
inline bool gethash(int depth);
void init(void);
void IDA(void);
int search(int depth,int color);
bool equ(int a,int b,int c,int d){
	if(a!=b||b!=c||c!=d)return 0;
	return 1;
}
inline bool check(void){
	for(int i=0;i<4;i++){
		if(equ(G[i][0],G[i][1],G[i][2],G[i][3]))return 1;
		if(equ(G[0][i],G[1][i],G[2][i],G[3][i]))return 1;
	}
	if(equ(G[0][0],G[1][1],G[2][2],G[3][3]))return 1;
	if(equ(G[0][3],G[1][2],G[2][1],G[3][0]))return 1;
	return 0;
}
inline bool gethash(int depth){
	int va=0;
	for(int i=0;i<4;i++)
		for(int j=0;j<4;j++)
			va=va*3+G[i][j];
	va%=4070017;
	if(hash[va]&&have[va]<=depth)return 0;//!!!!!!??????????
	have[va]=depth;
	return 1;
}
void IDA(void){
	for(k=1;k<=10;k++){
		search(1,1);
		if(ok){
			cout<<k;
			break;
		}
		else search(1,2);
		if(ok){
			cout<<k;
			break;
		}	
	}
	if(!ok)cout<<"wocao";
}
int search(int depth,int color){
	if(depth==k+1)return 0;
	for(int i=0;i<4;i++){
		int tx=ax+mx[i],ty=ay+my[i];
		if(tx<0||tx>3||ty<0||ty>3)continue;
		if(G[tx][ty]!=color)continue;
		swap(G[tx][ty],G[ax][ay]);
		ax=tx;ay=ty;
		if(gethash(depth)){
			if(check()){
				ok=1;
				return 1;
			}
			search(depth+1,3-color);
		}
		ax-=mx[i];ay-=my[i];
		swap(G[tx][ty],G[ax][ay]);
	}
	for(int i=0;i<4;i++){
		int tx=bx+mx[i],ty=by+my[i];
		if(tx<0||tx>3||ty<0||ty>3)continue;
		if(G[tx][ty]!=color)continue;
		swap(G[tx][ty],G[bx][by]);
		bx=tx;by=ty;
		if(gethash(depth)){
			if(check()){
				ok=1;
				return 1;
			}
			search(depth+1,3-color);
		}
		bx-=mx[i];by-=my[i];
		swap(G[tx][ty],G[bx][by]);
	}
}
void init(void){
	memset(hash,0,sizeof(hash));
	bool mark=0;
	for(int i=0;i<4;i++)
		for(int j=0;j<4;j++){
			char a;cin>>a;
			if(a=='B')G[i][j]=1;
			else if(a=='W')G[i][j]=2;
			else{
				G[i][j]=0;
				if(!mark){
					ax=i;ay=j;mark=1;
				}
				else{
					bx=i;by=j;
				}
			}
		}
}
int main(){
	init();
	IDA();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值