一道很好又简单的图的遍历
看到没人写图的遍历,就写一个吧
题目大意
有  和 
 ,求他们的差,如果是正数输出 
解法
可以将  五个数建成一个无向图,然后跑一边图的遍历,在边跑图的遍历时更新答案,输出即可
下面是代码:
//
#include <bits/stdc++.h>
#define ll long long
#define LM LLONG_MAX
#define IM INT_MAX
#define IMN INT_MIN
#define LMN LLONG_MIN
#define tr true
#define fa false 
using namespace std;
const int Maxm = 10;
int a[Maxm], ans[Maxm];
vector<int> g[Maxm];
bool f[Maxm];
void dfs(int x){		//跑一边图的遍历
	if(f[x]){		//如果被重复遍历到的话就退出
		return ;
	}
	f[x] = tr;
	ans[x] = (a[x] < a[5] ? a[5] - a[x] : 0);		//更新答案
	for(int i = 0; i < g[x].size(); i++){
		dfs(g[x][i]);
	}
}
int main(){
//  freopen(".in", "r", stdin);
//  freopen(".out", "w", stdout);
  for(int i = 1; i <= 5; i++){
  	cin >> a[i];
  }
  for(int i = 1; i <= 5; i++){
  	for(int j = 1; j <= 5; j++){
  		if(i != j){		//建边
  			g[i].push_back(j);
  			g[j].push_back(i);
  		}
  	}
  }
  dfs(5);
  for(int i = 1; i <= 4; i++){
  	cout << ans[i] << ' ';
  }
  cout << endl;
  return 0;		//完美收官
}  
如有错误,请指出,谢谢🙏

京公网安备 11010502036488号