uva 208 -Firetruck(dfs)

来源:互联网 发布:淘宝代购only是正品吗 编辑:程序博客网 时间:2024/05/12 05:04

题目点击打开链接

这个题目真的很坑!它的给的样例的格式是错误的,一直PE。。



然而事实上真正的格式应该是这样的

CASE 1:1 2 3 4 61 2 3 5 61 2 4 3 5 61 2 4 61 3 2 4 61 3 4 61 3 5 6There are 7 routes from the firestation to streetcorner 6.CASE 2:1 3 2 5 7 8 9 6 41 3 41 5 2 3 41 5 7 8 9 6 41 6 41 6 9 8 7 5 2 3 41 8 7 5 2 3 41 8 9 6 4There are 8 routes from the firestation to streetcorner 4.

差评 !!!!


这道题的目的是给你n个路牌之间的关系,然后给你一个路牌数,让你输出所有可行的路程

关于这道题的思路是用一个map[][]存储每个站之间关系然后 dfs寻找,用save去储存结果,注意dfs可能会超时,所以需要加一个visit来剪枝(标记已走过)



#include <iostream>#include<cstdio>#include<cstring>using namespace std;const int maxn=25;int map[maxn][maxn];int save[maxn];int visit[maxn];int  dfs(int s,int e,int d,int size)//  递归寻找{   int sum=0;//总路线数    if(s==e)// 到达目的地 输出    {   printf("1");        for(int i=1;i<d;i++)           printf(" %d",save[i]);           printf("\n");           return 1;    }    else    {        for(int i=2;i<=size;i++ )        {            if(!visit[i]&&map[i][e]&&map[s][i]==1) // 未拜访过,并且当前站下一站可为i,有i的路线经过目的站            {                visit[i]=1;//标记                save[d]=i;//储存路径                sum+=dfs(i,e,d+1,size); // 继续寻找下一个路                visit[i]=0;//            }        }    }    return sum;}int main(){    //freopen("out.txt","w",stdout);    int x,y;    int n;    int size=0;    int kase=0;    while(cin>>n)    {        memset(map,0,sizeof(map));        memset(visit,0,sizeof(visit));        memset(save,0,sizeof(save));        size=0;        while(cin>>x>>y&&x&&y)//        {            map[x][y]=1;            map[y][x]=1;            if(x>size)                size=x;            if(y>size)                size=y;        }        for(int k=1;k<=size;k++)   //处理各个站点,把可互通的并起来            for(int i=1;i<=size;i++)              for(int j=1;j<=size;j++)           {               if(!map[i][j]&&map[i][k]&&map[k][j])                map[i][j]=2;           }        printf("CASE %d:\n",++kase);        visit[1]=1;        save[0]=1;        printf("There are %d routes ",dfs(1, n, 1, size));        printf("from the firestation to streetcorner %d.\n",n);    }    return 0;}


0 0
原创粉丝点击