AtCoder Beginner Contest 225 D 模拟链表

本文介绍了一道关于车辆调度的问题,通过使用链表的数据结构来高效地解决车辆连接与查询的操作。采用前后指针的方式进行维护,使得每次操作都能快速完成。

题目

给你N个辆车 和Q次询问。
询问有3种
1:将a车放在b车后面,保证b车后面没车且a车前没车,保证两车相邻。
2:将a车从b车断开。保证两车相邻
3:查询a车所在的列有多少车,并且从后往前输出。
最多打印1e6的车次。

题解思路

链表题写少了,一开始没感觉出来,一直想着并查集,实际上只需维护一个点的前指针和后指针即可。

直接模拟链表是On级别的。
所以能过的很快。

AC代码
#include <bits/stdc++.h>
//#include <unordered_map>
#define PII pair<int,int>
#define ll long long

using namespace std;

const  int  INF =  0x3f3f3f3f;
const  int  N = 100100 ; 


vector <int> front(N,-1) ; 
vector <int> back(N,-1) ; 
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);
    int n , q ;
    cin >> n >> q ;
    while ( q-- )
    {
        int t1 , t2 ,t3 ;
        cin >> t1 ;
        if ( t1 == 1 )
        {
            cin >> t2 >> t3 ;
            front[t2] = t3 ;
            back[t3] = t2 ; 
        }else if ( t1 == 2 )
        {
            cin >> t2 >> t3 ;
            front[t2] = -1 ; 
            back[t3] = -1 ; 
        }else
        {
            vector <int> cs ;
            cin >> t3 ;
            int ps = t3 ; 
            while ( back[ps] != -1 )
                ps = back[ps] ;
            while ( ps != -1 )
            {
                cs.push_back(ps) ; 
                ps = front[ps] ; 
            }
            cout << cs.size() << " " ; 
            for ( auto & i : cs )
                cout << i << " ";
            cout << "\n" ;
        }
    }
    return 0 ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值