标签:
Description
Input
Output
Sample Input
4 5
Sample Output
11
Hint
OUTPUT DETAILS:
Bessie starts at 1 (barn), goes to 2, then 3, etc...
题目大意:给你一个N个点的图,M条双向边,从原点1出发,两个方向各走
一遍,最后回到原点。输出整个路径。从1开始,到1结束。共2*M+1行。
思路:DFS遍历,vis数组标记已遍历的边。
DFS的思想等效于先找一个环,然后对环上所有点递归DFS,并且把这些递归
产生的路插入这个环中。最重要的地方是在哪里保存路径。因为DFS函数的结
束顺序就是点的回溯顺序,所以应该在DFS回溯完之后再记录当前点的序号,
也就是now的值。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN = 10010;
const int MAXM = 100010;
int head[MAXN],N,M;
struct EdgeNode
{
int to;
int w;
int next;
};
EdgeNode Edges[MAXM];
int ans[MAXM],ansi;
bool vis[MAXM];
void DFS(int now)
{
int k;
for(k = head[now]; k != -1; k = Edges[k].next)
{
if(!vis[k])
{
vis[k] = true;
DFS(Edges[k].to);
}
}
ans[ansi++] = now;
}
int main()
{
while(cin >> N >> M)
{
int x,y;
memset(Edges,0,sizeof(Edges));
memset(head,-1,sizeof(head));
memset(ans,0,sizeof(ans));
memset(vis,0,sizeof(vis));
int j = 0;
for(int i = 0; i < M; ++i)
{
cin >> x >> y;
Edges[j].to = y;
Edges[j].w = 1;
Edges[j].next = head[x];
head[x] = j;
j++;
Edges[j].to = x;
Edges[j].w = 1;
Edges[j].next = head[y];
head[y] = j;
j++;
}
ansi = 0;
DFS(1);
for(int i = 0; i < ansi; ++i)
cout << ans[i] << endl;
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/lianai911/article/details/42098271