您的位置:首页 > 其它

[ZOJ 1008]Gnome Tetravex (dfs搜索 + 小优化)

2014-11-13 13:21 555 查看
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1008

题目大意:给你n*n的矩阵,每个格子里有4个三角形,分别是上右下左,每个三角形里面标记了数字,问你能否通过移动这n*n个格子,使得相邻两个三角形具有相同的数字?

dfs暴搜,dfs(x,y)代表当前要放(x,y)这个位置。

然后枚举给定的每个格子。

如果说可以放,就dfs下一个格子。

这一道题需要把相同的格子压缩起来,也就是说为了节省时间,可以记录相同的格子出现的次数。

然后对于这不同种的格子去dfs。

如果不这样做会超时。

这算是一种优化方法吧。涨姿势了。

#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <vector>
#include <map>
#include <set>
#include <iterator>
#include <functional>
#include <cmath>
#include <numeric>
#include <ctime>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;
#define PB push_back
#define MP make_pair
#define SZ size()
#define CL clear()
#define AA first
#define BB second
#define EPS 1e-8
#define ZERO(x) memset((x),0,sizeof(x))
const int INF = ~0U>>1;
const double PI = acos(-1.0);

int n;
int now[10][10];
bool vis[100];
int ptr;
bool flag;

struct Node{
int top,right,bottom,left;
int num;
bool operator==(const Node& b) const{
return top==b.top&&right==b.right&&bottom==b.bottom&&left==b.left;
}
Node(int t=0,int r=0,int b=0,int l=0):top(t),right(r),bottom(b),left(l){}
};
Node mp[100];

void dfs(int x,int y){
if(flag) return;
if( x==n || y==n ){
flag = true;
return;
}
for(int i=0;i<ptr;i++){
if( mp[i].num&&
(x==0||mp[now[x-1][y]].bottom==mp[i].top)
&&(y==0||mp[now[x][y-1]].right==mp[i].left) ){
now[x][y] = i;
mp[i].num--;
if( y+1<n ) dfs(x,y+1);
else dfs(x+1,0);
mp[i].num++;
}
}
}

int main(){
int kase = 1;
while(scanf("%d",&n),n){
ptr = 0;
for(int i=0;i<n*n;i++){
int t,r,b,l;
scanf("%d%d%d%d",&t,&r,&b,&l);
bool appear = 0;
for(int j=0;j<ptr;j++){
if(Node(t,r,b,l)==mp[j]){
mp[j].num++;
appear = 1;
}
}
if(!appear){
mp[ptr] = Node(t,r,b,l);
mp[ptr++].num = 1;
}
}

flag = false;
dfs(0,0);

if(kase!=1) puts("");
printf("Game %d: ",kase++);
puts(flag?"Possible":"Impossible");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: