思路:
题目所给图其实是一棵树,邻接表存图后,从根节点dfs一次就可以了,写的时候脑子瓦特了直接对所有点dfs就有个点超时了,对于相同长度的长链,是遍历两数组只要有一位不同就可以根据大小返回结果了,这个点我也wa了好几发。
代码:
#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
using namespace std;
typedef long long ll;
typedef pair<int, string> PII;
const int N = 1e4 + 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;
vector<int> a[N];
vector<int> res, t;
bool vis[N];
bool check(vector<int> a, vector<int> b)
{
for (int i = 0; i < a.size(); i++)
{
if (a[i] > b[i])
return true;
else if (a[i] < b[i])
return false;
}
return false;
}
void dfs(int x)
{
if (!a[x].size())
{
t.push_back(x);
if (t.size() > res.size() || t.size() == res.size() && check(res, t))
res = t;
t.pop_back();
}
else
{
for (auto p : a[x])
{
t.push_back(x);
dfs(p);
t.pop_back();
}
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int k;
cin >> k;
while (k--)
{
int x;
cin >> x;
a[i].push_back(x);
vis[x] = true;
}
}
int root;
for (int i = 0; i < n; i++) //找出根节点
{
if (!vis[i])
{
root = i;
break;
}
}
dfs(root);
cout << res.size() << endl;
for (int i = 0; i < res.size(); i++)
{
if (i != 0)
cout << ' ';
cout << res[i];
}
return 0;
}