题目链接:http://118.190.20.162/view.page?gpid=T34
思路: 1.DFS判断图的连通性 2.无向图判定欧拉路径定理 3.DFS序找欧拉路径
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <set>
using namespace std;
set<int> q[10000+10];
bool vis[10000+10][10000+10];
stack<int> result;
int next(int node) {
for (set<int>::iterator it = q[node].begin(); it != q[node].end(); it++) {
if (!vis[node][*it]) {
return *it;
}
}
return -1;
}
//不用模拟栈进行DFS的话只能得80分
void dfs(int x){
stack<int> S;
S.push(x);
while(!S.empty()){
int u=S.top();
int v=next(u);
if(v!=-1){
vis[u][v]=true;
vis[v][u]=true;
S.push(v);
}
else
{
S.pop();
result.push(u);
}
}
}
int graph_count;
bool vis_is_graph[10000+10];
void Judge_graph(int x){
graph_count++;
vis_is_graph[x]=1;
for(set<int>::iterator iter=q[x].begin();iter!=q[x].end();iter++){
if(!vis_is_graph[*iter]){
vis_is_graph[*iter]=true;
Judge_graph(*iter);
}
}
}
int n,m;
int main() {
cin>>n>>m;
for(int i=0;i<m;i++){
int s,t;
cin>>s>>t;
q[s].insert(t);
q[t].insert(s);
}
dfs(1);
bool path=true;
Judge_graph(1);
if(graph_count!=n){
path=false;
}
if(path) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (q[i].size() % 2 == 1) {
count++;
}
}
if (!(count == 0 || count == 2 && q[1].size() % 2 == 1)) {
path = false;
}
}
if(!path){
cout<<-1<<endl;
}
else
{
while(!result.empty()){
if(result.size()==1){
cout<<result.top();
}
else
{
cout<<result.top()<<" ";
}
result.pop();
}
}
return 0;
}