208:Firetruck

Firetruck

回溯即可,不過要注意先判斷是否可以到達着火點,如果到不了那就沒必要回溯了,可能給的數據比較坑,到不了的數據比較多,不判斷的話會超時。還有就是輸出的格式和樣例給的竟然不一樣,真是醉了。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 25;
int t, n, cnt2;
int vis[maxn], path[maxn];
int G[maxn][maxn];

int possible(){
    if(t == 1) return 1;
    int v[n+1] = {0};
    queue<int>q;
    q.push(1);
    v[1] = 1;
    while(!q.empty()){
        int u = q.front(); q.pop();
        for(int i = 2; i <= n; i++){
            if(!v[i] && G[u][i]){
                if(i == t) return 1;
                q.push(i);
                v[i] = 1;
            }
        }
    }
    return 0;
}
void DFS(int now, int cnt){
    if(now == t){
        for(int i = 0; i < cnt-1; i++){
            printf("%d ", path[i]);
        }
        printf("%d\n", t);
        cnt2++;
        return;
    }
    else{
        for(int i = 2; i <= n; i++){
            if(vis[i] || !G[now][i]) continue;
            vis[i] = 1;
            path[cnt] = i;
            DFS(i, cnt+1);
            vis[i] = 0;
        }
    }
}

int main()
{
    // freopen("data.in","r",stdin);
    // freopen("data.out","w",stdout);
    int a, b;
    int T = 1;
    path[0] = 1;
    while(scanf("%d", &t) !=  EOF){
        memset(G, 0, sizeof(G));
        n = cnt2 = 0;
        while(scanf("%d%d", &a, &b) == 2 && a && b){
            G[a][b] = G[b][a] = 1;
            n = max(n, max(a, b));
        }
        printf("CASE %d:\n", T++);
        if(possible()) DFS(1, 1);
        printf("There are %d routes from the firestation to streetcorner %d.\n", cnt2, t);
    }

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章