L2-2病毒溯源(关于内存超限这件事

在这里插入图片描述在这里插入图片描述
输入样例:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值