Pagini recente » Cod sursa (job #712164) | Cod sursa (job #1972931) | Cod sursa (job #352658) | Cod sursa (job #1599519) | Cod sursa (job #2819926)
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream in("ciclueuler.in");
ofstream out("ciclueuler.out");
class Graf {
int n;
int m;
vector<vector<int>> adj;
public:
Graf(int n, int m, vector<vector<int>> adj)
{
this->n = n;
this->m = m;
this->adj = adj;
}
void addEdge(int& x, int& y)
{
adj[x].push_back(y);
adj[y].push_back(x);
}
void removeEdge(int& x, int& y) {
for (int i = 0; i < adj[y].size(); ++i)
{
if (adj[y][i] == x)
{
swap(adj[y][i], adj[y][adj[y].size() - 1]);
adj[y].pop_back();
break;
}
}
for (int i = 0; i < adj[x].size(); ++i)
{
if (adj[x][i] == y)
{
swap(adj[x][i], adj[x][adj[x].size() - 1]);
adj[x].pop_back();
break;
}
}
}
void print()
{
int odd = 0;
for (int i = 1; i <= n; ++i)
{
if (adj[i].size() % 2 == 1)
{
odd++;
}
}
if (odd == 0)
{
odd++;
printEuler(odd);
}
else
{
out << -1;
}
}
void printEuler(int& nodp)
{
//out<<nodp<<" ";
if (adj[nodp].size() == 0)
{
return;
}
else
out << nodp << " ";
if (adj[nodp].size() == 1)
{
int nodc = adj[nodp][0];
removeEdge(nodp, nodc);
printEuler(nodc);
return;
}
for (auto nodc : adj[nodp])
{
if (nuPod(nodp, nodc))
{
removeEdge(nodp, nodc);
printEuler(nodc);
return;
}
}
}
bool nuPod(int & nodp, int & nodc)
{
int c1 = 0, c2 = 0;
vector<bool> visited;
removeEdge(nodp, nodc);
visited = vector<bool>(n + 1, false);
c1 = nrNod(nodc, visited);
addEdge(nodp, nodc);
visited = vector<bool>(n + 1, false);
c2 = nrNod(nodc, visited);
if (c2 == c1)
return true;
else
return false;
}
int nrNod(int & nodp, vector<bool>& visited)
{
visited[nodp] = true;
int count = 1;
for (auto nodc : adj[nodp])
{
if (visited[nodc] == false)
{
count += nrNod(nodc, visited);
}
}
return count;
}
};
int main()
{
int n, m, x, y;
in >> n >> m;
vector<vector<int>> adj(n + 1);
for (int i = 1; i <= m; ++i)
{
in >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
Graf g(n, m, adj);
g.print();
in.close();
out.close();
return 0;
}