您的位置:首页 > 其它

Union Find and search

2015-04-30 15:26 274 查看
1.POJ2488  A Knight's Journey

search

#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;

#define N 27
#define INF 0x7FFFFFFF
int p,q,_count=0;
int _dec

;
int routine[2*N];
int t1,t2;
int flag,flag2;

void path(int x,int y,int k)
{
switch (k)
{
case 0:{t1 = x-1;t2 = y-2;break;}
case 1:{t1 = x+1;t2 = y-2;break;}
case 2:{t1 = x-2;t2 = y-1;break;}
case 3:{t1 = x+2;t2 = y-1;break;}
case 4:{t1 = x-2;t2 = y+1;break;}
case 5:{t1 = x+2;t2 = y+1;break;}
case 6:{t1 = x-1;t2 = y+2;break;}
case 7:{t1 = x+1;t2 = y+2;break;}
}
}
void OUTPUT()
{
for (int i=0;i<_count;i++)
{
cout<<(char)('A'+routine[2*i+1])<<routine[2*i]+1;
if (i==_count-1) cout<<endl;
}
}
bool DFS(int x,int y)
{
if (flag2 == 1) return 0;
_dec[x][y]=1;
routine[2*_count]=x;
routine[2*_count+1]=y;
_count++;
if (_count>p*q)
{
flag2 = 1;
return 0;
}
if ((_count == p*q)&&(flag == 0))
{
OUTPUT();
flag = 1;
return 1;
}
for (int k=0;k<8;k++)
{
path(x,y,k);
int xx=t1,yy = t2;
if ((xx>=0)&&(xx<p)&&(yy>=0)&&(yy<q)&&(_dec[xx][yy]==0))
if (DFS(xx,yy)) return 1;
}
_dec[x][y]=0;
_count--;
return 0;
}
int main()
{
int n;
cin>>n;
for (int m=1;m<=n;m++)
{
for (int i=0;i<N;i++)
for (int j=0;j<N;j++)
_dec[i][j]=0;
memset(routine,0,sizeof(routine));
cin>>p>>q;
cout<<"Scenario #"<<m<<":"<<endl;
if ((p==1)&&(q==1))
{
cout<<"A1"<<endl<<endl;
continue;
}
if (p*q>26 || p>=9 || q>=9 || p<=2 || q<=2)
{
cout<<"impossible"<<endl<<endl;
continue;
}
_count = 0;
flag = 0;
flag2 = 0;
DFS(0,0);
if ((flag2 == 1)||(flag==0)) cout<<"impossible"<<endl;
cout<<endl;
}
return 0;
}


View Code
2.POJ 1077 Eight

/article/2328434.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: