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 @ 2022-03-17 14:05  banyanrong  阅读(34)  评论(0)    收藏  举报