208:Firetruck

Firetruck

回溯即可,不过要注意先判断是否可以到达着火点,如果到不了那就没必要回溯了,可能给的数据比较坑,到不了的数据比较多,不判断的话会超时。还有就是输出的格式和样例给的竟然不一样,真是醉了。

#include
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};
    queueq;
    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;
}

 

你可能感兴趣的:(算法,UVa,ACM-ICPC,水题,回溯,搜索,BFS,DFS)