• 瑞神要考研(并查集)


    1003: 瑞神要考研

    时间限制: 1 Sec  内存限制: 128 MB
    提交: 300  解决: 87
    [提交][状态][讨论版]

    题目描述

    瑞神要准备考研了,为了复习数据结构,瑞神在某宝上买了一本数据结构得考研辅导资料《考研数据结构---从入门到放弃》,从此瑞神开始了愉快的复(zhuang)习(bi)。 
    有一天,瑞神找了好多条链表来辅助自己复习,但是他在复习的过程中一不小心把链表掉在了地上,捡起来的时候链表以及断成了好多个结点,每个结点只保留了当前结点的地址、结点的值和下一个结点的地址。
    瑞神看着这些结点浑身难受无法复习,为了让瑞神继续复(zhuang)习(bi)下去,请你帮瑞神把链表复原。  

    输入

    第一行给出结点的个数 n(1<=n<=100000)。 
    接下来 n 行每行给出一个结点的信息:结点地址、值和下一个结点的地址。 
    地址为 5 位数字,-1 表示地址为 NULL。 
    保证每一条链表的最后一个结点的下一个结点地址为-1。   

    输出

    每一行输出一条链表,只输出每个节点的值。 
    多条链表按照首结点地址从小到大排序。 

    样例输入

    3
    00323 155 -1
    00322 87 00323
    00233 1 -1
    

    样例输出

    1
    87 155
    

    提示

    来源


    一道类似于模拟的题目。用一个并查集合并就好!!!

    #include <bits/stdc++.h>
    using namespace std;
     
    const int MAXN = 1e6 + 5;
     
    struct Node {
        //int pre;
        int val;
        int nxt;
    } node[MAXN];
     
    int fa[MAXN];
     
    int setFind(int x)
    {
        if (fa[x] < 0) {
            return x;
        }
        return fa[x] = setFind(fa[x]);
    }
     
    void setJoin(int x, int y)
    {
        x = setFind(x);
        y = setFind(y);
        if (x != y) {
            fa[y] = x;
        }
    }
     
    int main()
    {
        int n;
        int i;
        int a, b, c;
        set<int> st;
        set<int>::iterator it;
        int cur;
     
        while (~scanf("%d", &n)) {
            memset(fa, -1, sizeof(fa));
            st.clear();
            for (i = 0; i < n; ++i) {
                scanf("%d%d%d", &a, &b, &c);
                node[a].val = b;
                node[a].nxt = c;
                if (c != -1) {
                    setJoin(a, c);
                }
                st.insert(a);
            }
            for (it = st.begin(); it != st.end(); ++it) {
                //printf("%d, ", *it);
                if (fa[*it] < 0) {
                    cur = *it;
                    while (node[cur].nxt != -1) {
                        printf("%d ", node[cur].val);
                        cur = node[cur].nxt;
                    }
                    printf("%d
    ", node[cur].val);
                }
            }
        }
     
        return 0;
    }
     
    /**************************************************************
        Problem: 1003
        User: T035
        Language: C++
        Result: 正确
        Time:248 ms
        Memory:15244 kb
    ****************************************************************/







  • 相关阅读:
    传Windows 9预览版今秋发布
    谷歌上市十周年 成长为全球第二大技术公司
    Twitter CEO:有望进军中国 不会改变原则
    免费获得NOD32 半年、1年 激活码-14.08.12到期
    卡巴斯基正式版2015 简体中文版已经发布
    Google 宣布支持中文邮箱地址
    图片:走进柯达电影胶片厂
    Microsoft Visual Studio Ultimate 2013 with Update 3 CN+EN
    DataFrame衍生新特征操作
    isolation forest进行异常点检测
  • 原文地址:https://www.cnblogs.com/zswbky/p/8454158.html
Copyright © 2020-2023  润新知