#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m, S;
int w[N];
bool g[N][N];
vector<vector<int>> ans; //多维vector,相当于二维数组
void dfs(int u, int s, vector<int> &path) //u表示当前搜到了第几个点
//s表示当前总和
{
bool is_leaf = true;
for (int i = 0; i < n; i ++ ) //判断是否是叶子节点
if (g[u][i])
{
is_leaf = false;
break;
}
if (is_leaf)
{
if (s == S) ans.push_back(path); //如果答案是目标值,在答案中加入路径
}
else ///不是叶子节点
{
for (int i = 0; i < n; i ++ )
if (g[u][i])
{
path.push_back(w[i]); //搜索之前加入i的权值
dfs(i, s + w[i], path);
path.pop_back(); //搜完之后恢复现场
}
}
}
int main()
{
cin >> n >> m >> S;
for (int i = 0; i < n; i ++ ) cin >> w[i];
while (m -- ) //读入每条表
{
int id, k;
cin >> id >> k;
while (k -- ) //读入每个儿子
{
int son;
cin >> son;
g[id][son] = true;
}
}
vector<int> path({w[0]}); //path初始化
dfs(0, w[0], path); //从根节点开始暴搜
sort(ans.begin(), ans.end(), greater<vector<int>>()); //答案排序(从大到小
for (auto p : ans) //输出所有路径
{
cout << p[0]; //p是一个vector
for (int i = 1; i < p.size(); i ++ ) cout << ' ' << p[i];
cout << endl;
}
return 0;
}
1053 Path of Equal Weight (30分) ♡
最新推荐文章于 2023-12-01 11:22:43 发布
本文详细介绍了一种使用深度优先搜索(DFS)算法解决路径寻找问题的方法。通过递归方式遍历图的所有可能路径,寻找从起点到终点的可行路径,并在找到目标路径时将其记录下来。文章还介绍了如何使用C++实现这一算法,包括如何定义图结构、存储顶点权重、建立邻接矩阵以及进行深度优先搜索的具体过程。
2769

被折叠的 条评论
为什么被折叠?



