天天看點

L2-002. 連結清單去重(用兩個隊列來儲存兩個連結清單)

題目連結:https://www.patest.cn/contests/gplt/L2-002

思路: 用兩個隊列來儲存兩個連結清單,注意格式輸出就好,還要注意不存在 被删除連結清單的情況

代碼:

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <queue>

using namespace std;

const int maxn =+;


struct Edge
{
    int key,next;
} e[maxn];

int flag[maxn];

int main()
{
    typedef pair<int,int> p;//第一個值為位址,第二個為鍵值
    queue<p>l,l1;
    int N,fir_add,address,x,flag1=;
    memset(flag,,sizeof(flag));
    scanf("%d %d",&fir_add,&N);
    for(int i=; i <N; i++)
    {
        scanf("%d",&address);
        scanf("%d %d",&e[address].key,&e[address].next);
    }
    while(fir_add!=-)
    {
        x=abs(e[fir_add].key);
        if(flag[x]==)
        {
            l.push((p)
            {
                fir_add,e[fir_add].key
            });
            flag[x]=;
        }
        else
        {
            l1.push((p)
            {
                fir_add,e[fir_add].key
            });
        }
        fir_add=e[fir_add].next;
    }
    p p1;
    p1=l.front();
    l.pop();
    printf("%05d %d ",p1.first,p1.second);
    while(!l.empty())
    {
        p1=l.front();
        l.pop();
        printf("%05d\n",p1.first);
        printf("%05d %d ",p1.first,p1.second);
    }
    printf("-1\n");
    if(!l1.empty())
    {
        flag1=;
        p1=l1.front();
        l1.pop();
        printf("%05d %d ",p1.first,p1.second);
    }
    while(!l1.empty())
    {
        p1=l1.front();
        l1.pop();
        printf("%05d\n",p1.first);
        printf("%05d %d ",p1.first,p1.second);
    }
    if(flag1)
    printf("-1\n");

    return ;
}