题目链接
给出一些路径,让求能经过的最长路径及其经过的点的序列,如果最长路径不唯一,输出最小序列
#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排下序,然后按照这个顺序找到的一定是最小序列。