POJ2230 Watchcow
作者:互联网
Watchcow
Time Limit: 3000MS | Memory Limit: 65536K | |||
Total Submissions: 9914 | Accepted: 4286 | Special Judge |
Description
Bessie's been appointed the new watch-cow for the farm. Every night, it's her job to walk across the farm and make sure that no evildoers are doing any evil. She begins at the barn, makes her patrol, and then returns to the barn when she's done.If she were a more observant cow, she might be able to just walk each of M (1 <= M <= 50,000) bidirectional trails numbered 1..M between N (2 <= N <= 10,000) fields numbered 1..N on the farm once and be confident that she's seen everything she needs to see. But since she isn't, she wants to make sure she walks down each trail exactly twice. It's also important that her two trips along each trail be in opposite directions, so that she doesn't miss the same thing twice.
A pair of fields might be connected by more than one trail. Find a path that Bessie can follow which will meet her requirements. Such a path is guaranteed to exist.
Input
* Line 1: Two integers, N and M.* Lines 2..M+1: Two integers denoting a pair of fields connected by a path.
Output
* 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.Sample Input
4 5 1 2 1 4 2 3 2 4 3 4
Sample Output
1 2 3 4 2 1 4 3 2 4 1
Hint
OUTPUT DETAILS:Bessie starts at 1 (barn), goes to 2, then 3, etc...
Source
USACO 2005 January Silver给你一个N个点的图,M条双向边,从原点1出发,两个方向各走一遍。最后回到1。输出整个路径。从1開始。到1结束。共2*M+1行。
题解
其实就是求欧拉回路,只不过这题要求每条边正反走两遍。
那么不记录vis数组表示无向边的经过情况,这样就会走两次了。
时间复杂度\(O(m)\),手动模拟dfs来避免爆栈。
#include<iostream>
#define rg register
#define il inline
#define co const
template<class T>il T read(){
rg T data=0,w=1;rg char ch=getchar();
for(;!isdigit(ch);ch=getchar())if(ch=='-') w=-w;
for(;isdigit(ch);ch=getchar()) data=data*10+ch-'0';
return data*w;
}
template<class T>il T read(rg T&x) {return x=read<T>();}
typedef long long ll;
co int N=1e4+1,M=1e5+2;
int head[N],ver[M],next[M],tot;
int stack[M],ans[M]; // 模拟系统栈,答案栈
int n,m,top,t;
il void add(int x,int y){
ver[++tot]=y,next[tot]=head[x],head[x]=tot;
}
int main(){
read(n),read(m),tot=1;
for(int i=1,x,y;i<=m;++i) read(x),read(y),add(x,y),add(y,x);
stack[++top]=1;
while(top){
int x=stack[top],i=head[x];
if(i){
stack[++top]=ver[i];
head[x]=next[i];
}
else{
--top;
ans[++t]=x;
}
}
for(int i=t;i;--i) printf("%d\n",ans[i]);
return 0;
}
标签:ch,int,Watchcow,tot,read,POJ2230,barn,she 来源: https://www.cnblogs.com/autoint/p/10951971.html