题解:AT_abc421_f [ABC421F] Erase between X and Y

· · 题解

很容易想到用链表。每一个点又只会查询一次,因为查完之后就删了,所以可以暴力查询,有一个需要注意的点就是,需要向前向后同时查找,当一个查到时另一个停止,这样才能保住复杂度,考虑如果我们能只找对的方向,那么每个点只会被扫一次就是 O(n) 的,那么每次不正确的那一边加起来最多也扫 O(n) 次。

先向一边找的话会退化成 O(n^2)。

代码。

#include <bits/stdc++.h>
typedef long long ll;
#define ls cur << 1
#define rs cur << 1 | 1
using namespace std;
const int N = 1e6 + 10;
int pre[N], nxt[N];
int main()
{
     ios :: sync_with_stdio(0);
     cin.tie(0);
     cout.tie(0);
     int q; cin >> q;
     nxt[0] = -1;
     for(int i = 1; i <= q; i ++ )
     {
        int op; cin >> op;
        if(op == 1)
        {
            int x; cin >> x;
            int nn = nxt[x];
            pre[i] = x;
            nxt[x] = i;
            if(nn != -1)pre[nn] = i; 
            nxt[i] = nn;
         }
         else
         {
            int x, y; cin >> x >> y;
            if(x == y) {cout << 0 << '\n'; continue;}
            int xx = x;
            int yy = y;
            ll ans = 0, res = 0;
            while(1)
            {
                if(xx == y || yy == x) break;
                if(nxt[xx] != -1)
                {
                    ans += xx;
                    xx = nxt[xx];   
                 }
                 if(nxt[yy] != -1)
                 {
                    res += yy;
                    yy = nxt[yy];
                 }
            }
            if(xx == y){
            ans -= x;
            nxt[x] = y;
            pre[y] = x;
            cout << ans << '\n';
            }
            else{
            res -= y;
            nxt[y] = x;
            pre[x] = y;
            cout << res << '\n';
            }
         }
     }
    return 0;
}