HDU2181(DFS)

题目连接


题解:直接DFS传入当前城市如果当前城市是m则返回去寻找父城市直到m判断是访问的城市个数是否为19个如果是就输出否则继续运用stack


#include<cstring>
#include<cstdio>
#include<iostream>
#include<string>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<stack>
#include<functional>
using namespace std;
#define eb(x) push_back(x)
#define pb(x) push_back(x)
#define ps(x) push(x)
#define clr(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f
#define MAX_N 100+5
#define MAX_M 10005
typedef long long ll;
typedef priority_queue<int,vector<int>,less<int> > pql;
typedef priority_queue<int,vector<int>,greater<int> >pqg;
struct Next
{
    int nex[4];
    void input()
    {
        for(int i=0; i<3; i++)
        {
            scanf("%d",&nex[i]);
        }
        sort(nex,nex+3);
    }
} q[25];
int m,tot,vis[25],f[25];
stack<int> sta;
void dfs(int cur)
{
    if(cur==m)
    {
        int tm=f[cur];
        sta.ps(m);
        while(tm!=m)
        {
            sta.ps(tm);
            tm=f[tm];
        }
        sta.ps(m);
        if(sta.size()==21)
        {
            cout<<++tot<<": ";
            while(!sta.empty())
            {
                cout<<" "<<sta.top();
                sta.pop();
            }
            cout<<endl;
        }
        else
        {
            while(!sta.empty())
            {
                sta.pop();
            }
        }
        return ;
    }
    for(int i=0; i<3; i++)
    {
        int to=q[cur].nex[i];
        if(vis[to]==0)
        {
            vis[to]=1;
            f[to]=cur;
            dfs(to);
            vis[to] = 0;
        }
    }
}
int main()
{
    //freopen("data.txt","r",stdin);
    for(int i=1; i<=20; i++)
    {
        q[i].input();
    }
    while(~scanf("%d",&m)&&m)
    {
        clr(vis,0);
        clr(f,0);
        tot=0;
        for(int i=0; i<3; i++)
        {
            int to=q[m].nex[i];
            if(vis[to]==0)
            {
                vis[to]=1;
                f[to]=m;
                dfs(to);
            }
            vis[to]=0;
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值