Sequence
Problem Description
We define an element a_iai in a sequence "good", if and only if there exists a j(1\le j < i)j(1≤j<i) such that a_j < a_iaj<ai.
Given a permutation pp of integers from 11 to nn. Remove an element from the permutation such that the number of "good" elements is maximized.
Input
The input consists of several test cases. The first line of the input gives the number of test cases, T(1\le T\le 10^3)T(1≤T≤103).
For each test case, the first line contains an integer n(1\le n\le 10^6)n(1≤n≤106), representing the length of the given permutation.
The second line contains nn integers p_1,p_2,\cdots,p_n(1\le p_i\le n)p1,p2,⋯,pn(1≤pi≤n), representing the given permutation pp.
It’s guaranteed that \sum n\le 2\times 10^7∑n≤2×107.
Output
For each test case, output one integer in a single line, representing the element that should be deleted. If there are several answers, output the minimal one.
Sample Input
2 1 1 5 5 1 2 3 4
Sample Output
1 5
题意:在一个数列中,假如一个数比在它之前出现的任意一个数大,那么它是一个好数,现在必须删去一个数,使剩余的数好数最多,多个解输出最小值.
思路:当时思路是看看每个数删去之后会减少多少好数,假如一个数前面比他小的只有一个,那么删去那个数这个数也就不再是好数,所以我们可以看看比当前数小的是不是只出现了一个,是的话那个最小值的度++.开始想写树状数组,后来想起来维护一个次小值即可.
代码:
#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const double esp = 1e-12;
const int inf = 0x3f3f3f3f;
map<int,int>::iterator it;
int n;
int a[maxn],d[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
mem(d,0);
scanf("%d",&n);
for(int i = 1;i<= n;i++)
scanf("%d",&a[i]);
int minx1 = inf,minx2;//最小值和次小值
for(int i = 1;i<= n;i++)
{
if(a[i]> minx1) d[a[i]]++;//是好数自己度++
if(a[i]> minx1&&a[i]< minx2)
d[minx1]++;//前面有唯一的比他小的值,那个数的度++
if(a[i]< minx1)
minx2 = minx1,minx1 = a[i];//更新最小次小值
else minx2 = min(minx2,a[i]);//更新次小值
}
int ans,ansd = inf;
for(int i = 1;i<= n;i++)
{
if(d[a[i]]< ansd)
ansd = d[a[i]],ans = a[i];
else if(d[a[i]] == ansd)
ans = min(ans,a[i]);
}
printf("%d\n",ans);
}
return 0;
}