Remove Extra One
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a permutation of length . Remove one element from permutation to make the number of records the maximum possible.
We remind that in a sequence of numbers the element is a record if for every integer the following holds: .
input
The first line contains the only integer — the length of the permutation.
The second line contains integers — the permutation. All the integers are distinct.
Output
Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.
Examples
Input
1
1
Output
1
Input
5
5 1 2 3 4
Output
5
Note
In the first example the only element can be removed.
解題思路
先給一波官方題解:
In this problem you have to find an element after which removal the number of records is maximum possible.
Let ri be an array consisting of 0 and 1 depending on whether the element was a record initially or not. We can compute it easily in .
Let be the difference between the number of records after removal the i-th element and initial number of records.
Let’s think of how does removal of ai influence the array . First of all, becomes 0. do not change in this case. Some of , change from 0 to 1. These elements are not records initially, but become records after the removal. These elements are elements which have only one greater element in front of them — .
Here follows an solution. Let’s fix — the element we are going to remove. Let + the number of such that , , and for all We can compute this just looping through all and keeping the maximum over all elements but the .
Now note that it’s not required to fix . can become 1 from 0 only when a certain element from the left is removed. Let’s loop through all and determine if there is an element to the left such that it is greater than , but all other elements are less than . We can check this using ordered set. If there is such a , then increase by 1. After the loop the array is fully computed, so we can just find the element which brings the maximum number of records, and minimum among such.
一個元素比它前面的所有元素都大,稱此元素爲 。
首先用一個標記數組 表示第i個元素是(1)否(0)是 ,在 時間內可以求出。
然後考慮移除一個元素 後,能影響哪些 ?
自身。還有:在他之後的,某些原本不是 的,因爲 的移除,成爲 的。
這些 (稱爲 )有這樣的特點:比從1到 除 外的元素都大,但不比 大。
記從1到 除 外的元素的最大值爲 ,則可表示爲 。此不等式爲本題“題眼”。
這樣就有了官方的 解法:枚舉要移除的元素 ->檢查 及在他之後的 ,計算 增量->得移除後能使 最大的元素。
然而BB半天, 數據,顯然超時。
這時候想想“題眼”,那個神奇的不等式。
同樣設(刪除 後的)增量數組 , 順推並維護 和 不就可以了?
如果 ,說明 是 , ,並更新 爲 , 爲 ;
如果 ,“題眼”, (注意是 ),並更新 爲 。
最後的問題,如果存在相同的元素,映射不唯一,一首涼涼?
回頭審題, ,計劃通,代碼非常簡單。
小坑點,第一個元素是不算 的。
AC代碼
#include<bits/stdc++.h>
using namespace std;
int a[100050];
int main()
{
int n;
while(cin>>n){
memset(a,0,sizeof(a));
int x,m2nd=0,m1st=0;
for(int i=1;i<=n;i++){
cin>>x;
if(x>m1st){
m2nd=m1st;
m1st=x;
a[x]--;
}
else if(x>m2nd){
m2nd=x;
a[m1st]++;
}
}
int ma=-0x3f3f3f3f,mi;
for(int i=1;i<=n;i++)
if(a[i]>ma)
ma=a[i],mi=i;
printf("%d\n",mi);
}
return 0;
}