CCCC L2-002. 链表去重

https://www.patest.cn/contests/gplt/L2-002

模拟一个链表的去重操作

题解:别模拟了,直接用内置的list和map。关于输出的地址,直接用pair存地址和值,输出时按地址 值 下一个元素的地址 输出。

坑:之前头铁,模拟了半天,各种错误。

然后直接用list  注意删除,输出的细节。删除是常规技巧。输出时注意判掉最后一个节点,输出-1. 关于如何访问list的next:直接it++

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include<stack>
#include<set>
#include<string.h>
#include<list>
#define pb push_back
#define mp make_pair
#define _for(i, a, b) for (int i = (a); i<(b); ++i)
#define _rep(i, a, b) for (int i = (a); i <= (b); ++i)

using namespace std;
const  int N = 100000 + 5;
//double num[N], price[N], ave[N];
int nxt[N], val[N];
int nxt1[N];
map<int, int> p;
list<pair<int, int> >l,ll;
int main() {
    int head, n;
    cin >> head >> n;
    _for(i, 0, n) {
        int x;
        cin >> x;
        cin >> val[x] >> nxt[x];

    }

    for (int p = head; p != -1; p = nxt[p]) {
        l.push_back(mp(p, val[p]));
    }
    
    list<pair<int, int> >::iterator it;
    for (it = l.begin(); it != l.end();){
    if (p.count(abs(it->second))) {
        ll.push_back(*it);
        it = l.erase(it);
    }
    else p[abs(it->second)]++, it++;
}
    for (it = l.begin(); it != l.end(); ) {
        printf("%05d %d ", it->first, it->second);
        //cout << it->first << ' ' << it->second << ' ';
        if (++it != l.end())printf("%05d\n", it->first);//cout<< it->first << endl;
            else cout << -1 << endl;
    }
    for (it = ll.begin(); it != ll.end(); ) {
        printf("%05d %d ", it->first, it->second);
        //cout << it->first << ' ' << it->second << ' ';
        if (++it != ll.end())printf("%05d\n", it->first);//cout<< it->first << endl;
        else cout << -1 << endl;
    }
    system("pause");


}
/*
  00100 5
99999 15 87654
23854 15 00000
87654 15 -1
00000 15 99999
00100 15 23854
*/
/*
00100 -15 23854
23854 -15 00000
00000 21 99999
99999 -7 87654
87654 15 -1
00000 21 -1
*/

 

posted @ 2018-03-29 10:24  SuuTTT  阅读(163)  评论(0编辑  收藏  举报