2022.10.31每日一题
Daimayuan Online Judge-序列维护
题目描述
你有一个序列,现在你要支持几种操作:
-
insert x y
,在从前往后的第 \(x\) 个元素后面插入 \(y\) 这个数。如果 \(x=0\),那么就在开头插入。 -
delete x
,删除从前往后的第 \(x\) 个元素。 -
query k
,询问从前往后数第 \(k\) 个元素是多少。
输入格式
第一行一个整数 \(m\),表示操作个数。
接下来 \(m\) 行,每行一个上面所述的操作。
输出格式
输出若干行,对于每个查询操作,输出答案。
样例输入
10
insert 0 1
insert 1 2
query 1
query 2
insert 0 3
query 1
delete 1
query 1
insert 1 4
query 2
样例输出
1
2
3
1
4
数据范围
对于 \(100\%\) 的数据,保证 \(m≤10^3\)。
对于insert
操作,保证 \(1≤y≤10^9\)。
对于所有操作,保证位置不会超出当前序列的长度。
解题思路
链表模拟。
C++代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1010;
int n, head = -1;
int e[N], ne[N], idx;
void add(int k, int x)
{
int i, j;
for(i = head, j = 1; i != -1 && j <= k; i = ne[i], j ++)
continue;
e[idx] = x;
ne[idx] = ne[i];
ne[i] = idx ++;
}
void add_to_head(int x)
{
e[idx] = x;
ne[idx] = head;
head = idx ++;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
while(n --)
{
string op;
cin >> op;
if(op == "insert")
{
int x, y;
cin >> x >> y;
if(x == 0) add_to_head(y);
else add(x - 1, y);
}
else if(op == "delete")
{
int x;
cin >> x;
if(x == 1)
head = ne[head];
else
{
int i, j;
for(i = head, j = 1; i != -1 && j <= x - 2; i = ne[i], j ++)
continue;
ne[i] = ne[ne[i]];
}
}
else
{
int k, res;
cin >> k;
for(int i = head, j = 1; i != -1 && j <= k; i = ne[i], j ++)
res = e[i];
cout << res << endl;
}
}
return 0;
}
原文地址:http://www.cnblogs.com/Cocoicobird/p/16848037.html
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。