HDU 2181 哈密顿绕行世界问题(水DFS)

该题乍看很难的样子,其实就是个水DFS,因为要打印所有可能方案,所以无法剪枝,直接遍历所有可能情况就行。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;
int T,n,m,a,b,c,kase,ans[maxn],vis[maxn];
vector<int> g[maxn];
void dfs(int d, int cur) {
    if(d == 20) {
        bool ok = false;
        int len = g[cur].size();
        for(int i=0;i<len;i++) {
            if(g[cur][i] == m) { ok = true; break; }
        }
        if(!ok) return ;
        printf("%d:  ",++kase);
        printf("%d",ans[0]);
        for(int i=1;i<20;i++) printf(" %d",ans[i]);
        printf(" %d\n",m);
        return ;
    }
    int len = g[cur].size();
    for(int i=0;i<len;i++) {
        int u = g[cur][i];
        if(!vis[u]) {
            vis[u] = 1;
            ans[d] = u;
            dfs(d+1,u);
            vis[u] = 0;
        }
    }
}
int main() {
    for(int i=1;i<=20;i++) {  // 输入,去除重复元素
        scanf("%d%d%d",&a,&b,&c);
        bool ok = true;
        for(int j=0;j<g[i].size();j++)
        if(g[i][j] == a) { ok = false; break; }
        if(ok) g[i].push_back(a);
        ok = true;
        for(int j=0;j<g[i].size();j++)
        if(g[i][j] == b) { ok = false; break; }
        if(ok) g[i].push_back(b);
        ok = true;
        for(int j=0;j<g[i].size();j++)
        if(g[i][j] == c) { ok = false; break; }
        if(ok) g[i].push_back(c);
        ok = true;
        for(int j=0;j<g[a].size();j++)
        if(g[a][j] == i) { ok = false; break; }
        if(ok) g[a].push_back(i);
        ok = true;
        for(int j=0;j<g[b].size();j++)
        if(g[b][j] == i) { ok = false; break; }
        if(ok) g[b].push_back(i);
        ok = true;
        for(int j=0;j<g[c].size();j++)
        if(g[c][j] == i) { ok = false; break; }
        if(ok) g[c].push_back(i);
    }
    for(int i=1;i<=20;i++)
        sort(g[i].begin(), g[i].end()) ;
    while(~scanf("%d",&m)&&m) {
        memset(vis,0,sizeof(vis));
        kase=0;
        ans[0] = m;
        vis[m] = 1;
        dfs(1,m);
    }
    return 0;
}


你可能感兴趣的:(搜索,HDU,DFS,暴力,ACM-ICPC)