习题7-1 uva 208(剪枝)

题意:按最小字典序输出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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值