习题7-1 uva 208(剪枝)

来源:互联网 发布:html小游戏源码 编辑:程序博客网 时间:2024/04/30 01:14

题意:按最小字典序输出a到b 的所有路径。

思路:先处理出个点到目标点b的情况(是否能到达),搜索即可。

最开始我只判了a能否到b,然后给我的是WA,然后看了半天感觉思路没什么问题,然后把所有点都处理出来,AC

实在是看不懂- -,好无语。


#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <queue>#include <algorithm>typedef long long ll;using namespace std;int tmap[200][200];const int inf = 0x3f3f3f3f;int ans[200];int can[200];int n,a,b;int tmax;int vis[200];int all;void dfs(int cur,int num){    if(cur == n)    {        printf("1");        for(int i = 1; i < num; i++)            printf(" %d",ans[i]);        printf("\n");        all++;        return ;    }    for(int i = 1; i <= tmax; i++)    {        if(!vis[i] && tmap[cur][i] && can[i])        {            vis[i] = 1;            ans[num] = i;            dfs(i,num+1);            vis[i] = 0;        }    }    return ;}void get_can(int cur)      //是否能到达终点{    can[cur] = 1;    for(int i =1 ; i <= tmax; i++)        if(tmap[cur][i] && !can[i])            get_can(i);}int main(){    int cas = 1;    while(scanf("%d",&n)!=EOF)    {        memset(vis,0,sizeof(vis));        memset(can,0,sizeof(can));        memset(tmap,0,sizeof(tmap));        while(scanf("%d %d",&a,&b))        {            if(a == 0 && b == 0)                break;            tmap[a][b] = tmap[b][a] = 1;            if(a > tmax)                tmax = a;            if(b > tmax)                tmax = b;        }        get_can(n);        printf("CASE %d:\n",cas++);        if(!can[n])        {            printf("There are 0 routes from the firestation to streetcorner %d.\n",n);            continue;        }        vis[1] = 1;        all = 0;        dfs(1,1);        printf("There are %d routes from the firestation to streetcorner %d.\n",all,n);    }    return 0;}



0 0
原创粉丝点击