uva 321 - The New Villa

数组G开20*20会在poj re,但在uva会ac

在poj G开到200*200才ac掉,ac也郁闷。。。

poj 1137 http://poj.org/problem?id=1137

#include <iostream>

#include<cstdio>

#include<cstring>

#include<cmath>

#include<algorithm>

using namespace std;

int r,d,s,cas=1;

bool vis[100000],G[200][200];



int Switch[15][15],top[15];

struct node

{

    int step;

    int st;

    int p;

    int fa;

}q[100000];

bool insert(int t)

{

    int h=q[t].st*10+q[t].p-1;

    if(vis[h])

    return false;

    return vis[h]=true;

}

int bit(int x)

{

    for(int i=0;i<15;i++)

    if((1<<i)==x)

    return i+1;

}

void print_path(int y)

{

    int x=q[y].fa;

    if(y)

    print_path(x);

    if(q[x].p!=q[y].p)

    printf("- Move to room %d.\n",q[y].p);

    else if(q[x].st<q[y].st)

    printf("- Switch on light in room %d.\n",bit(q[y].st-q[x].st));

    else if(q[x].st>q[y].st)

    printf("- Switch off light in room %d.\n",bit(q[x].st-q[y].st));

}

void bfs()

{

    memset(vis,false,sizeof(vis));

    int a=0,b=1;

    q[0].fa=0,q[0].step=0,q[0].st=1,q[0].p=1;

    insert(0);

    while(a<b)

    {

        int x=q[a].p,y;

        if(x==r&&q[a].st==(1<<(r-1)))

        {

            printf("The problem can be solved in %d steps:\n",q[a].step);

            print_path(a);

            return;

        }

        for(int i=1;i<=r;i++)

        if(G[x][i]&&(1<<(i-1))&q[a].st)

        {

            q[b].fa=a;

            q[b].p=i;

            q[b].step=q[a].step+1;

            q[b].st=q[a].st;

            if(insert(b))

            b++;

        }

        for(int i=0;i<top[x];i++)

        {

            y=Switch[x][i];

            q[b].fa=a;

            q[b].p=x;

            if((1<<(y-1))&q[a].st)

            q[b].st=q[a].st-(1<<(y-1));

            else

            q[b].st=q[a].st+(1<<(y-1));

            q[b].step=q[a].step+1;



            if(1<<(x-1)&q[b].st&&insert(b))

            b++;

        }

        a++;

    }

    puts("The problem cannot be solved.");

}

int main()

{

    while(scanf("%d%d%d",&r,&d,&s),r+d+s)

    {

        memset(top,0,sizeof(top));

        //memset(head,-1,sizeof(head));

        memset(G,false,sizeof(G));

        for(int i=0;i<d;i++)

        {

            int x,y;

            scanf("%d%d",&x,&y);

            G[x][y]=G[y][x]=true;

        }

        for(int i=0;i<s;i++)

        {

            int x,y;

            scanf("%d%d",&x,&y);

            Switch[x][top[x]++]=y;

        }

        for(int i=1;i<=s;i++)

        for(int j=0;j<top[i];j++)

        for(int k=j+1;k<top[i];k++)

        if(Switch[i][j]>Switch[i][k])

        {

            int t=Switch[i][j];

            Switch[i][j]=Switch[i][k];

            Switch[i][k]=t;

        }

        printf("Villa #%d\n",cas++);

        bfs();

        puts("");

    }

    return 0;

}

  

你可能感兴趣的:(new)