L2-038 病毒溯源 (25 分)

该程序通过深度优先搜索找到图中的最长路径,并在路径不唯一时保证输出的序列是最小的。代码首先读取节点数和边的信息,然后使用DFS遍历所有可能的路径,更新最长路径和对应的节点序列。最终输出最长路径长度和路径上的节点序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
给出一些路径,让求能经过的最长路径及其经过的点的序列,如果最长路径不唯一,输出最小序列

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <sstream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

using namespace std;

vector<int> e[10010], temp, ans;
int n, maxx = -1;
bool book[10010];
int que[10010];

void dfs(int u, int k)
{
	if (k > maxx)//如果路径长度比现有长度更长
	{
		maxx = k;//更新最大长度
		ans = temp;//更新最大长度的序列
	}
	for (int i = 0; i < e[u].size(); i++)
	{
		temp.push_back(e[u][i]);//模拟每一步
		dfs(e[u][i], k + 1);
		temp.pop_back();//不要忘记pop出来
	}
	return;
}

int main(int argc, char const *argv[])
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int t;
		cin >> t;
		while (t--)
		{
			int x;
			cin >> x;
			book[x] = 1;
			e[i].push_back(x);
		}
		sort(e[i].begin(), e[i].end());//从小到大排序,这样如果能找到最大路径的话一定是最小序列
	}
	int flag;//病毒源头
	for (int i = 0; i < n; i++)
		if (book[i] == 0)
		{
			flag = i;
			break;
		}
	dfs(flag, 0);
	printf("%d\n", maxx + 1);
	printf("%d", flag);
	for (int i = 0; i < ans.size(); i++)
		printf(" %d", ans[i]);
	printf("\n");
	return 0;
}

用temp模拟每个点放进去拿出来的过程,然后用ans记录当前最长路径的序列,如果发现更长的就用temp更新ans,最小序列用一个sort排下序,然后按照这个顺序找到的一定是最小序列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值