This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
constexpr size_t N = 1000;
vector<size_t> g[N];
pair<size_t, size_t> find_farthest(size_t u, size_t p = -1)
{
size_t x = u, y = 0;
for (size_t const &v : g[u])
if (v != p)
{
auto [w, d] = find_farthest(v, u);
if (d > y)
x = w, y = d;
}
return {x, y + 1};
}
bool find_path(size_t dest, vector<size_t> &path, size_t u, size_t p = -1)
{
if (u == dest)
{
path.push_back(u);
return 1;
}
for (size_t const &v : g[u])
if (v != p)
{
if (find_path(dest, path, v, u))
{
path.push_back(u);
return 1;
}
}
return 0;
}
vector<size_t> find_diameter()
{
auto [u, _] = find_farthest(0);
auto [v, d] = find_farthest(u);
vector<size_t> diameter;
find_path(v, diameter, u);
return diameter;
}
void walk_diameter(vector<size_t> const &diameter, vector<size_t> &a)
{
for (size_t i = 1; i < diameter.size() - 1; ++i)
{
size_t u = diameter[i];
a.push_back(u);
for (size_t v : g[u])
if (g[v].size() != 1 && find(diameter.begin(), diameter.end(), v) == diameter.end())
a.push_back(v), a.push_back(u);
}
}
int main()
{
size_t n, m;
cin >> n >> m;
if (m != n - 1)
{
cout << "NO\n";
return 0;
}
if (n == 1)
{
cout << "YES\n1\n1\n";
return 0;
}
if (n == 2)
{
cout << "YES\n2\n1 1\n";
return 0;
}
for (size_t i = 0; i < m; ++i)
{
size_t u, v;
cin >> u >> v;
g[u - 1].push_back(v - 1);
g[v - 1].push_back(u - 1);
}
vector<size_t> diameter = find_diameter();
for (size_t i = 0; i < n; ++i)
if (g[i].size() != 1)
{
bool can_escape = find(diameter.begin(), diameter.end(), i) == diameter.end();
for (size_t v : g[i])
can_escape &= find(diameter.begin(), diameter.end(), v) == diameter.end();
if (can_escape)
{
cout << "NO\n";
return 0;
}
}
cout << "YES\n";
vector<size_t> a;
walk_diameter(diameter, a);
reverse(diameter.begin(), diameter.end());
walk_diameter(diameter, a);
cout << a.size() << '\n';
for (size_t u : a)
cout << u + 1 << ' ';
cout << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |