7.8 训练参考(待更新
Firetruck:
较为简单的dfs,注意对于正在访问的结点的vis标记,同时如果有TLE的错误,需要先判断1是否能到达k,因为如果这是一个1-19的全通图,但是到达不了20,dfs是需要19!远远大于11,肯定会超时的
点击查看代码
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
constexpr int MAXN = 20+5;
int n, ans = 0, des = 0;
bool vis[MAXN], G[MAXN][MAXN];
vector<int> out;
bool getD() {
if(scanf("%d", &n) != 1) return false;
int x, y;
ans = des = 0; out.clear();
memset(G, 0,sizeof(G));
memset(vis, 0, sizeof(vis));
while(scanf("%d%d", &x, &y) && x && y) {
G[x][y] = G[y][x] = true;
if(x > des) des = x;
if(y > des) des = y;
}
return true;
}
void dfs(int pos) {
out.push_back(pos);
if(pos == n) {
ans++;
int len = out.size();
for(int i = 0; i < len; i++) {
cout << out[i];
if(i!=len-1) cout << " ";
else cout << endl;
}
}
for(int i = 1; i <= des; i++) {
if(G[pos][i]) {
if(vis[i]) continue;
vis[i] = true;
dfs(i);
out.erase(out.end()-1);
vis[i] = false;
}
}
}
bool check(int pos) {
vis[pos] = true;
if(pos == n) return true;
for(int i = 1; i <= des; i++) {
if(G[pos][i] && !vis[i])
if(check(i)) return true;
}
return false;
}
int main() {
int kase = 0;
while(getD()) {
cout << "CASE " << ++kase << ":" << endl;
if(!check(1)) {
cout << "There are " << ans << " routes from the firestation to streetcorner " << n << "." << endl;
continue;
}
memset(vis, 0, sizeof(vis));
vis[1] = true;
dfs(1);
cout << "There are " << ans << " routes from the firestation to streetcorner " << n << "." << endl;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)