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;
}
posted @   banyanrong  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示