UVa-208 Firetruck

来源:互联网 发布:编辑midi的软件 编辑:程序博客网 时间:2024/06/03 07:23

UVA-208

天道好轮回。UVA饶过谁。

就是一个图的DFS。

不过这个图的边太多,要事先判一下起点和终点是否联通(我喜欢用并查集),否则会TLE。


#include <iostream>#include <cstdio>#include <vector>#include <cstring>#define maxn 40using namespace std;int a[maxn][maxn], vis[maxn], ans, f[maxn];vector<int> q;int build(int x, int y){    a[x][y] = 1;    a[y][x] = 1;}int found(int x){    if (f[x] == x) return x;    f[x] = found(f[x]);    return f[x];}int add(int x, int y){    int fx = found(x), fy = found(y);    if (fx != fy) f[fx] = fy;}void DFS(int k, int n){    if (k == n)    {        for (int i = 0; i < q.size()-1; i++)            cout << q[i] << " ";        cout << q[q.size()-1] << endl;        ans++;    }    for (int  i = 1; i <= maxn / 2; i++)        if (!vis[i] && a[k][i])        {            vis[i] = 1;            q.push_back(i);            DFS(i, n);            q.pop_back();            vis[i] = 0;        }}int main(){    int n, cases = 0;    while (cin >> n)    {        memset(a, 0, sizeof(a));        memset(vis, 0, sizeof(vis));        for (int i = 1; i <= maxn/2; i++) f[i] = i;        ans = 0;        while (!q.empty()) q.pop_back();        int x, y;        while (cin >> x >> y && x && y)        {            build(x, y);            add(x, y);        }        ++cases;        printf("CASE %d:\n", cases);        q.push_back(1);        vis[1] = 1;        if (found(1) == found(n)) DFS(1, n);        printf("There are %d routes from the firestation to streetcorner %d.\n", ans, n);    }}


原创粉丝点击