好久没有写题目了
看了一天了,一看就是dfs可以解决的,
下面代码超时
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
struct node
{
int u, r, d, l;
};
int map[6][6];
int n, m, t=0, cnt, num[25], ans;
node g[25];
void
dfs(int p)
{
if(ans){
return;
}
if(p==m){
ans=1;
return;
}
int i, x, y;
for(i=0; i<cnt; i++){
if(num[i]==0)continue;
x=p/n;
y=p%n;
if(x>0 && g[map[x-1][y]].d!=g[i].u)continue;
if(y>0 && g[map[x][y-1]].r!=g[i].l)continue;
map[x][y]=i;
num[i]--;
dfs(p+1);
if(ans)return;
num[i]++;
}
}
int
main()
{
int u, r, l, d;
int i, k, t=0;
while(cin>>n && n){
m=n*n;
cnt=0;
memset(num, 0, sizeof(num));
for(i=0; i<m; i++){
cin>>u>>r>>d>>l;
for(k=0; k<cnt; k++)
if(g[k].u==u && g[k].r==r && g[k].l==l && g[k].d==d)
break;
if(k==cnt){
g[k].u==u;
g[k].r==r;
g[k].l==l;
g[k].d==d;
cnt++;
num[k]=l;
}
else
num[k]++;
}
ans=0;
dfs(0);
if(t)
cout<<endl;
cout<<"Game "<<t<<": ";
if(ans)
cout<<"Impossible"<<endl;
else
cout<<"Possible"<<endl;
}
}
改为纯c语言
#include <stdio.h>
#include <cstring>
struct node
{
int u, r, d, l;
};
int map[6][6];
int n, m, t=0, cnt, num[25], ans;
node g[25];
void
dfs(int p)
{
if(ans){
return;
}
if(p==m){
ans=1;
return;
}
int i, x, y;
for(i=0; i<cnt; i++){
if(num[i]==0)continue;
x=p/n;
y=p%n;
if(x>0 && g[map[x-1][y]].d!=g[i].u)continue;
if(y>0 && g[map[x][y-1]].r!=g[i].l)continue;
map[x][y]=i;
num[i]--;
dfs(p+1);
if(ans)return;
num[i]++;
}
}
int
main()
{
int u, r, l, d;
int i, k, t=0;
while(scanf("%d", &n), n){
m=n*n;
cnt=0;
memset(num, 0, sizeof(num));
for(i=0; i<m; i++){
scanf("%d%d%d%d", &u, &r, &d, &l);
for(k=0; k<cnt; k++)
if(g[k].u==u && g[k].r==r && g[k].l==l && g[k].d==d)
break;
if(k==cnt){
g[k].u==u;
g[k].r==r;
g[k].l==l;
g[k].d==d;
cnt++;
num[k]=l;
}
else
num[k]++;
}
ans=0;
dfs(0);
if(t)
printf("\n");
printf("Game %d: ", t);
if(ans)
printf("Impossible\n");
else
printf("Possible\n");
}
}
反正我是没办法了 题目时间是10s都过不了,后台数据有多大呀
伤不起