直接上
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int MAXN = 3005;
int n;
int arr[MAXN]; // 存储原始输入数组
int result[MAXN][MAXN]; // 存储计算结果
int topLength[MAXN]; // 记录每个元素的顶部长度
int stack[MAXN]; // 模拟栈
int top = 0; // 栈顶指针
int exist[MAXN]; // 标记元素是否存在
int count[MAXN]; // 记录每个结果的出现次数
// 快速读取整数
inline int read() {
int x = 0;
char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)) {
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
return x;
}
// 快速输出整数
inline void write(int x) {
if (x >= 10) write(x / 10);
putchar(x % 10 + 48);
}
// 重新计算结果
void recalculate(int current, int previous = 0) {
int flag = 0;
top = 0;
std::memset(exist, 0, sizeof(exist));
std::memset(topLength, 0, sizeof(topLength));
// 遍历数组,更新栈和顶部长度
for (int i = 1; i <= n; ++i) {
if (arr[i] == current) {
while (top > 0) {
int element = stack[top--];
topLength[element] += 2;
if (!flag) topLength[element]--;
exist[element] = 0;
}
flag = 1;
} else if (!exist[arr[i]]) {
exist[arr[i]] = 1;
stack[++top] = arr[i];
}
}
// 处理栈中剩余元素
while (top > 0) {
int element = stack[top--];
topLength[element]++;
exist[element] = 0;
}
// 更新结果矩阵和计数数组
if (previous) {
for (int i = 1; i <= n; ++i) {
if (i != current && i != previous) {
--count[result[i][current]];
result[i][current] = 1;
}
--count[result[current][i]];
}
}
for (int i = 1; i <= n; ++i) {
result[current][i] = flag ? topLength[i] + 1 : 1;
++count[result[current][i]];
}
}
int main() {
n = read();
for (int i = 1; i <= n; ++i) arr[i] = read();
// 初始化计算结果
for (int i = 1; i <= n; ++i) {
recalculate(i);
}
// 找到最大的有效结果
int answer = 1;
for (int i = n; i > 1; --i) {
if (count[i]) {
answer = i;
break;
}
}
write(answer);
putchar('\n');
int query = read();
while (query--) {
int index = read();
int value = read();
int previousValue = arr[index];
if (arr[index] != value) {
arr[index] = value;
recalculate(previousValue, value);
recalculate(value, previousValue);
}
// 重新找到最大的有效结果
answer = 1;
for (int i = n; i > 1; --i) {
if (count[i]) {
answer = i;
break;
}
}
write(answer);
putchar('\n');
}
return 0;
}