2 条题解

  • 0
    @ 2026-7-20 1:42:56

    B3631 单向链表——题解

    思路

    由于元素值最大只有 10610^6 且互不相同,可以用数组 nxt[x] 直接记录元素 x 后面的元素。

    • 插入 yx 后面:先令 nxt[y]=nxt[x],再令 nxt[x]=y
    • 查询 x 后面:输出 nxt[x],末尾的后继本来就是 00
    • 删除 x 后面:令 nxt[x]=nxt[nxt[x]]。若 nxt[x]==0,数组的零号位置也为 00,操作自然保持不变。

    复杂度

    每条操作时间复杂度 O(1)O(1),空间复杂度 O(106)O(10^6)

    参考代码

    #include <bits/stdc++.h>
    using namespace std;
    
    int nxt[1000005];
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int q;
        cin >> q;
        while (q--) {
            int op, x, y;
            cin >> op >> x;
            if (op == 1) {
                cin >> y;
                nxt[y] = nxt[x];
                nxt[x] = y;
            } else if (op == 2) {
                cout << nxt[x] << '\n';
            } else {
                nxt[x] = nxt[nxt[x]];
            }
        }
        return 0;
    }
    
    • 0
      @ 2026-7-20 1:42:56

      #include <bits/stdc++.h> using namespace std; int nxt[1000005]; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int q; cin>>q; while(q--){ int op,x,y; cin>>op>>x; if(op1){ cin>>y; nxt[y]=nxt[x]; nxt[x]=y; } else if(op2) cout<<nxt[x]<<'\n'; else nxt[x]=nxt[nxt[x]]; } return 0; }

      • 1

      信息

      ID
      4944
      时间
      1000ms
      内存
      128MiB
      难度
      10
      标签
      递交数
      2
      已通过
      2
      上传者