//给你一幅连通的图,要求从起点1开始走,要经过每条边刚好两次,
//并且最终回到1起点,很明显,欧拉回路,dfs输出路径即可。
/*
//邻接矩阵表示法,超时
#include <iostream>
using namespace std;
const int VETEX_NUM = 10002;
const int EDGE_NUM = 50002;
int adj[VETEX_NUM][VETEX_NUM]; //adj[节点][边]=节点
int stack[VETEX_NUM*2];
bool vis[EDGE_NUM*2];
int nv, ne, ne2, top;
void euler(int cur)
{
for (int i = 0; i < ne2; ++i){
if (!vis[i] && adj[cur][i]){
vis[i] = true;
euler(adj[cur][i]);
stack[top++] = adj[cur][i];
}
}
}
int main()
{
int i, u, v;
scanf("%d%d", &nv, &ne);
for (i = 1; i <= ne; ++i){
scanf("%d%d", &u, &v);
adj[u][ne2++] = v;
adj[v][ne2++] = u;
}
euler(1);
printf("%d\n");
for (i = top-1; i >= 0; --i){
printf("%d\n", stack[i]);
}
return 0;
}
*/
//邻接表
#include <iostream>
using namespace std;
struct E
{
int v, next;
bool vis;
};
const int VETEX_NUM = 10002;
const int EDGE_NUM = 50002;
E e[EDGE_NUM*2];
int head[VETEX_NUM], stack[EDGE_NUM*2];
int nv, ne, ne2, top;
//寻找欧拉路径,遍历所有节点,对于每个节点,遍历所有与它相连的路径
void euler(int cur)
{
for (int i = head[cur]; i != -1; i = e[i].next){
if (!e[i].vis){
e[i].vis = true;
euler(e[i].v);
printf("%d\n", e[i].v);
//stack[top++] = e[i].v;
}
}
}
int main()
{
int i, u, v;
scanf("%d%d", &nv, &ne);
memset(head, -1, sizeof(head));
for (i = 1; i <= ne; ++i){
scanf("%d%d", &u, &v);
//邻接表的构建,将最新的邻接节点插入到链表头
e[ne2].v = v;
e[ne2].next = head[u]; //插入到链表头
head[u] = ne2++; //更新链表头位置
e[ne2].v = u;
e[ne2].next = head[v];
head[v] = ne2++;
}
euler(1);
printf("1\n");
return 0;
}
POJ 2230 (欧拉回路)
最新推荐文章于 2021-03-18 21:13:56 发布