链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
题目描述
You are given a forest. Find a Hamiltonian path for its complement graph or determine if it does not contain any Hamiltonian path.
A forest is a graph with no cycles.
A Hamiltonian path is a path which visits every vertex exactly once.
A graph GGG's complement graph is a graph HHH on the same vertices such that two distinct vertices of HHH are adjacent if and only if they are not adjacent in GGG.
输入描述:
The first line contains one integer TTT (1≤T≤1051\le T \le 10^51≤T≤105), representing the number of test cases. For each test case, the first line contains two integers n,mn,mn,m (2≤n≤5⋅1052\le n \le 5 \cdot 10^52≤n≤5⋅105, 0≤m≤n−10 \le m \le n - 10≤m≤n−1), representing the number of vertices and the number of edges. The following mmm lines each contain two integers u,vu,vu,v (1≤u,v≤n1\le u,v \le n1≤u,v≤n, u≠vu \neq vu=v), representing an edge. It is guaranteed that the given graph is a forest, and ∑n≤106\sum n \le 10^6∑n≤106.
输出描述:
For each test case, if it is impossible to find a Hamiltonian path on the graph's complement, output −1-1−1 in a single line. Otherwise, output nnn distinct integers p1,p2…pnp_{1},p_{2} \dots p_{n}p1,p2…pn (1≤pi≤n1\le p_{i} \le n1≤pi≤n) in a line, where edge (pi,pi+1)(p_{i},p_{i+1})(pi,pi+1) (1≤i<n1\le i < n1≤i<n) is in GGG's complement graph. If there are multiple answers, output any.
示例1
输入
复制5 3 2 1 2 2 3 2 0 4 3 1 2 2 3 2 4 5 2 1 5 2 3 5 4 1 2 1 3 2 4 2 5
5 3 2 1 2 2 3 2 0 4 3 1 2 2 3 2 4 5 2 1 5 2 3 5 4 1 2 1 3 2 4 2 5
输出
复制-1 1 2 -1 2 1 4 3 5 1 5 4 3 2
-1 1 2 -1 2 1 4 3 5 1 5 4 3 2
题目意思给你一个森林,求补图的哈密顿路径。(搜索就可以)
特判菊花图,3个点的菊花图。
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define pb push_back
#define endl "\n"
#define fir first
#define sec second
typedef long long ll;
const int N=5e5+5;
int n,m,k,t;
int vis[N],in[N],dep[N];
vector<int>g[N],depv[N];
int maxdep;
void init() {
maxdep=0;
for(int i=1; i<=n; i++) {
vis[i]=0;
in[i]=0;
dep[i]=0;
depv[i].clear();
g[i].clear();
}
}
void dfs(int x,int pa) {
vis[x]=1;
dep[x]=dep[pa]+1;
maxdep=max(maxdep,dep[x]);
depv[dep[x]].pb(x);
for(auto i:g[x]) {
if(i==pa)continue;
dfs(i,x);
}
}
void func(int x) {
for(int v:depv[x])cout<<v<<" ";
}
void slove() {
cin>>n>>m;
init();
if(n==3&&m==1) { //特判
int a,b;
cin>>a>>b;
cout<<a<<" "<<6-a-b<<" "<<b<<endl;
return ;
}
for(int i=0; i<m; i++) {
int a,b;
cin>>a>>b;
g[a].pb(b);
g[b].pb(a);
in[a]++;
in[b]++;
}
for(int i=1; i<=n; i++) { //菊花图特判
if(in[i]==n-1) {
cout<<-1<<endl;
return ;
}
}
for(int i=1; i<=n; i++) {
if(!vis[i]&&in[i]<=1) {
dep[0]=maxdep;//不同的森林的起点深度
dfs(i,0);
}
}
for(int i=2; i<=maxdep; i+=2)func(i);
for(int i=1; i<=maxdep; i+=2)func(i);
cout<<endl;
}
signed main() {
IOS
cin>>t;
while(t--) {
slove();
}
return 0;
}