zoukankan      html  css  js  c++  java
  • Day4

    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...
     
    思路:打印欧拉通路,题目保证有解,直接DFS打印即可,代码如下:
    const int maxm = 10010;
    const int maxn = 50010;
    
    struct Node {
        int from, to;
        Node(int _from, int _to) : from(_from), to(_to){}
    };
    
    int N, M, vis[maxn*2];
    vector<int> ans, G[maxm];
    vector<Node> edges;
    
    void addedge(int u,int v) {
        edges.push_back(Node(u, v));
        G[u].push_back(edges.size() - 1);
    }
    
    void dfs(int x) {
        int len = G[x].size();
        for(int i = 0; i < len; ++i) {
            if(!vis[G[x][i]]) {
                vis[G[x][i]] = 1;
                dfs(edges[G[x][i]].to);
                ans.push_back(edges[G[x][i]].to);
            }
        }
    }
    
    int main() {
        scanf("%d%d", &N, &M);
        for (int i = 0; i < M; ++i) {
            int t1, t2;
            scanf("%d%d", &t1, &t2);
            addedge(t1, t2);
            addedge(t2, t1);
        }
        dfs(1);
        int len = ans.size();
        for(int i = 0; i < len; ++i)
            printf("%d
    ", ans[i]);
        printf("1
    ");
        return 0;
    }
    View Code
  • 相关阅读:
    一条代码快速解决滚动条隐藏问题
    微信小程序:wx:for循环输出的使用方法以及简单例子
    点运算符(.)和中括号运算符([])有哪些区别
    线程
    ArrayMap 和HashMap的区别
    Android加载图片的策略
    Android图片加载为什么选择glide
    Android 设计模式对比
    Android 注解框架对比
    ReactNative编写规范
  • 原文地址:https://www.cnblogs.com/GRedComeT/p/11285674.html
Copyright © 2011-2022 走看看