hdu1252

来源:互联网 发布:java解析syslog协议 编辑:程序博客网 时间:2024/06/08 03:48
蒟蒻的自我拯救。。。
#include<iostream>#include<string.h>#include<queue>#define PROCESS a=min3(next.p1,next.p2,next.p3);c=max3(next.p1,next.p2,next.p3);b=next.p1+next.p2+next.p3-a-c;if( hash[a][b][c] )    continue;hash[a][b][c]=true;next.dist=cur.dist+1;if( a==c )    return next.dist;Q.push(next);using namespace std;char graph[51][51];bool hash[51][51][51];typedef struct{    int p1,p2,p3,dist;}node;node sn;int n;int max3(int a,int b,int c){    return (a<b?a:b)<c?(a<b?a:b):c;}int min3(int a,int b,int c){    return (a>b?a:b)>c?(a>b?a:b):c;}int bfs(void){    queue<node> Q;    int a,b,c;    if( sn.p1==sn.p2 && sn.p2==sn.p3 )        return 0;    memset(hash,false,sizeof(hash));    sn.dist=0;    a=min3(sn.p1,sn.p2,sn.p3);    c=max3(sn.p1,sn.p2,sn.p3);    b=sn.p1+sn.p2+sn.p3-a-c;    hash[a][b][c]=true;    Q.push(sn);    while( !Q.empty() )    {        node cur=Q.front();        Q.pop();        for(int i=1;i<=n;i++)        {            node next=cur;            if( graph[next.p1][i] != graph[next.p2][next.p3] )    continue;            next.p1=i;            PROCESS        }        for(int i=1;i<=n;i++)        {            node next=cur;            if( graph[next.p2][i] != graph[next.p1][next.p3] )    continue;            next.p2=i;            PROCESS        }        for(int i=1;i<=n;i++)        {            node next=cur;            if( graph[next.p3][i] != graph[next.p1][next.p2] )    continue;            next.p3=i;            PROCESS        }    }    return -1;}int main(){    int ans;    while( cin>>n ,n )    {        cin>>sn.p1>>sn.p2>>sn.p3;        for(int i=1;i<=n;i++)            for(int j=1;j<=n;j++)                cin>>graph[i][j];        ans=bfs();        if( ans!=-1 )    cout<<ans<<endl;        else cout<<"impossible"<<endl;    }    return 0;}

0 0
原创粉丝点击