NC51343. Watchcow
描述
输入描述
* Line 1: Two integers, N and M.
* Lines 2..M+1: Two integers denoting a pair of fields connected by a path.
输出描述
* Lines 1..2M+1: A list of fields she passes through, one per line, beginning and ending with the barn at field 1. If more than one solution is possible, output any solution.
示例1
输入:
4 5 1 2 1 4 2 3 2 4 3 4
输出:
1 2 3 4 2 1 4 3 2 4 1
说明:
Bessie starts at 1 (barn), goes to 2, then 3, etc...C++14(g++5.4) 解法, 执行用时: 32ms, 内存消耗: 3236K, 提交时间: 2019-12-06 11:13:27
#include<bits/stdc++.h> using namespace std; char buf[1<<20],*_=buf,*__=buf; #define gc() (_==__&&(__=(_=buf)+fread(buf,1,1<<20,stdin),_==__)?EOF:*_++) #define TT template<class T>inline TT bool read(T &x){ x=0;char c=gc(); while(c<48||c>57)c=gc(); while(47<c&&c<58)x=(x<<3)+(x<<1)+(c^48),c=gc(); return 1; } TT bool read(T&a,T&b){return read(a)&&read(b);} const int MAXN=1e4+8; struct E{int y,nt;}e[MAXN*10]; int head[MAXN],cnt; inline void add(int x,int y){ e[++cnt].y=y; e[cnt].nt=head[x]; head[x]=cnt; } int n,m; void dfs(int x){ for(int i=head[x];head[x]=e[i].nt,i;i=head[x]){ head[x]=e[i].nt; dfs(e[i].y); } printf("%d\n",x); } int main() { read(n,m); for(int i=0,x,y;i<m;++i)read(x,y),add(x,y),add(y,x); dfs(1); return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 23ms, 内存消耗: 1656K, 提交时间: 2020-06-08 14:23:16
#include<bits/stdc++.h> using namespace std; const int maxn=1e6+10; int head[maxn],Next[maxn],to[maxn],tot; int st[maxn],ans[maxn];bool vis[maxn]; int n,m,top,t; void add(int x,int y) { to[++tot]=y,Next[tot]=head[x],head[x]=tot; } void euler() { st[++top]=1; while(top>0){ int x=st[top],i=head[x]; //while(i&&vis[i]) i=Next[i]; if(i){ st[++top]=to[i]; //vis[i]=vis[i^1]=true; head[x]=Next[i]; }else{ top--;ans[++t]=x; } } } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ int t1,t2;scanf("%d%d",&t1,&t2); add(t1,t2);add(t2,t1); } euler(); for(int i=t;i;i--){ printf("%d\n",ans[i]); } }