#include <bits/stdc++.h>
using namespace std;
const int maxn = 22;
int u, v, kase, eend, route[maxn], numRoute;
bool vis[maxn], used[maxn], G[maxn][maxn];
set<int>edge;
void bfs(int u)
{
queue<int>que;
que.push(u);
while (!que.empty())
{
int t = que.front(); que.pop();
for (auto it = edge.begin(); it != edge.end(); it++)
if (!used[*it] && G[t][*it])
{
used[*it] = true;
que.push(*it);
}
}
}
void dfs(int cur, int u)
{
if (u == eend)
{
++numRoute;
for (int i = 0; i < cur; i++)
cout << route[i] << (i == cur - 1 ? "\n" : " ");
}
else for (auto it = ++edge.begin(); it != edge.end(); it++)
if (used[*it] && G[u][*it] && !vis[*it])
{
vis[*it] = 1;
route[cur] = *it;
dfs(cur + 1, *it);
vis[*it] = 0;
}
}
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
while (cin >> eend)
{
edge.clear();
memset(G, 0, sizeof(G));
memset(vis, 0, sizeof(vis));
memset(used, 0, sizeof(used));
while (cin >> u >> v && u || v)
{
edge.insert(u), edge.insert(v);
G[u][v] = G[v][u] = 1;
}
used[eend] = 1;
bfs(eend);
cout << "CASE " << ++kase << ":" << endl;
vis[1] = 1, route[0] = 1, numRoute = 0;
dfs(1, 1);
cout << "There are " << numRoute << " routes from the firestation to streetcorner " << eend << "." << endl;
}
return 0;
}
事实证明,set很慢,我只是插入几组数而已,直接从ac到了tle 。。。