#include <bits/stdc++.h>
#define int long long
#define sz(a) (int)a.size()
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
using namespace std;
vector<vector<int>> neigh;
vector<int> lngst;
vector<int> sz;
vector<int> ans;
int n;
int mx;
int mxI;
int mxI2;
bool np=false;
pair<int,int> dfs(int x, int p){
int cmx1=0;
int cmx2=0;
int cmxI=x;
int cmxI2=-1;
for (auto u : neigh[x])
{
if(u==p) continue;
pair<int,int> df=dfs(u,x);
if(df.first>cmx1){
cmx2=cmx1;
cmxI2=cmxI;
cmx1=df.first;
cmxI=df.second;
}else if(df.first>cmx2){
cmx2=df.first;
cmxI2=df.second;
}
if(cmx1+cmx2>mx){
mx=cmx1+cmx2;
mxI=cmxI;
mxI2=cmxI2;
}
}
return {cmx1+1,cmxI};
}
void color(int x, int p){
for (auto u : neigh[x])
{
if(u==p) continue;
color(u,x);
}
if(x==mxI2) { lngst[x]=true; mxI2=p; }
return;
}
int findsz(int x, int p){
sz[x]=1;
for (auto u : neigh[x])
{
if(u==p) continue;
sz[x]+=findsz(u,x);
}
if(!lngst[x]&&sz[x]>2) np=true;
return sz[x];
}
void solve(int x, int p){
int nxt=-1;
if(x!=mxI&&x!=mxI2) ans.push_back(x);
for (auto u : neigh[x])
{
if(u==p) continue;
if(lngst[u]) nxt=u;
else if(sz[u]==1) continue;
else {
ans.push_back(u);
ans.push_back(x);
}
}
if(nxt>=0) solve(nxt, x);
return;
}
signed main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
int m; cin >> n >> m;
neigh.resize(n);
sz.resize(n);
lngst.resize(n);
mx=0; mxI=0;
for (int i = 0; i < m; i++)
{
int a,b; cin >> a >> b; a--; b--;
neigh[a].push_back(b);
neigh[b].push_back(a);
}
if(n==1){
cout << "YES\n" << "1\n"<< "1\n";
return 0;
}
if(m>=n) {
cout<< "NO\n";
return 0;
}
dfs(0,-1);
int root=mxI;
color(root,-1);
findsz(root,-1);
if(np){
cout << "NO\n";
return 0;
}
solve(root,-1);
cout << "YES\n";
cout << sz(ans)*2 << "\n";
for (int i = 0; i < sz(ans); i++) cout << ans[i]+1 << " ";
for (int i = 0; i < sz(ans); i++) cout << ans[sz(ans)-i-1]+1 << " ";
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |