输入样例:
10
3 6 4 8
0
0
0
2 5 9
0
1 7
1 2
0
2 3 1
输出样例:
4
0 4 9 1
这道题其实不难,为什么专门记一下是因为我第一次写的时候内存超限了…第一次遇到这个情况,我开始以为是因为dfs递归导致的,本来想着要不用非递归写dfs,不想写就搜了一下发现的确的dfs的原因,但不是因为递归…
void dfs(int root,vector<int> temp) {
temp.push_back(root);
for (int i = 0; i < childs[root].size(); i++) {
dfs(childs[root][i], temp);
}
if (childs[root].size() == 0 && temp.size() > finalPath.size()) {
finalPath = temp;
}
}
这是第一遍的dfs,看一下和下面的有什么差别,没错传入的是一个vector<int> temp,我每次递归都是传入一个vector<int> temp,也就是说我每一次递归都要开辟一个新的空前放置…这内存够大的…我之前好像都是这个写法,今天终于翻车了。
然后就有了后面这个写法,直接传入地址,这样使用的就一直是初始的那一块空间,后序不会因为递归开辟新的空间存放之前的vector。(说的不够专业,但大概意思应该表述出来了)
嗯,不是个大问题,也不算个小问题。记着了!
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<stack>
using namespace std;
const int N = 1e4 + 5;
vector<vector<int>>childs;
vector<int> finalPath;
bool notRoot[N];
void dfs(int root, vector<int>& temp) {
if (temp.size() > finalPath.size())
finalPath = temp;
for (int i = 0; i < childs[root].size(); i++) {
temp.push_back(childs[root][i]);
dfs(childs[root][i], temp);
temp.pop_back();
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int k;
cin >> k;
vector<int> v;
while (k--) {
int x;
cin >> x;
notRoot[x] = true;
v.push_back(x);
}
sort(v.begin(), v.end());
childs.push_back(v);
}
//找到根
int root = -1;
for (int i = 0; i < n; i++) {
if (!notRoot[i]) root = i;
}
vector<int> temp;
temp.push_back(root);
dfs(root,temp);
cout << finalPath.size() << endl;
for (int i = 0; i < finalPath.size(); i++) {
if (i) cout << " ";
cout << finalPath[i];
}
return 0;
}