去重链表

题目链接:https://www.patest.cn/contests/gplt/L2-002


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <cstring>


using namespace std;


const int inf = 1e6 + 10;
struct node{
char af[10];
char bf[10];
int val;
}th[inf];


int b[inf];
int s[inf];
int k1, k2;
bool fou[inf];
int main()
{
    memset(fou, false, sizeof(fou));
    char head[10];
    int num;
    scanf("%s %d", &head, &num);
    getchar();
    int k = 0;
    for(int i = 0; i < num; i ++){
        char u[10], v[10];
        int val;
        scanf("%s %d %s", &u, &val, &v);
        strcpy(th[atoi(u)].af, u);
        strcpy(th[atoi(u)].bf, v);
        th[atoi(u)].val = val;
        //cout << th[atoi(u)].af << " " <<  th[atoi(v)].bf << endl;
    }
    while(atoi(head) != -1){
        if(!fou[abs(th[atoi(head)].val)]){
            fou[abs(th[atoi(head)].val)] = true;
            b[k1 ++] = atoi(head);
        }else {
            s[k2 ++] = atoi(head);
        }
        strcpy(head, th[atoi(head)].bf);
    }
    for(int i = 0; i < k1; i ++){
        cout << th[b[i]].af << ' ' << th[b[i]].val << ' ';
        if(i != k1 - 1) cout << th[b[i + 1]].af;
        else cout << -1;
        cout << endl;
        //cout << b[i] << " ";
    }
    for(int i = 0; i < k2; i ++){
        cout << th[s[i]].af << ' ' << th[s[i]].val << ' ';
        if(i != k2 - 1) cout << th[s[i + 1]].af;
        else cout << -1;
        cout << endl;
        //cout << s[i] << ' ';
    }
    return 0;

}

用for循环解复杂度太高了,所以用结构体来存每个节点,然后每个节点的存在结构体数组里的位置用本节点的地址来充当,因为不会重复,可以用atoi函数来将字符串化为整数,然后注意下输出就好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值