Problem Description
We define an element a_iai in a sequence "good", if and only if there exists a j(1le 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(1le Tle 10^3)T(1≤T≤103).
For each test case, the first line contains an integer n(1le nle 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(1le p_ile n)p1,p2,⋯,pn(1≤pi≤n), representing the given permutation pp.
It’s guaranteed that sum nle 2 imes 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
思路:首先要明白,一个不好数,它总是它之前(包括它)出现的所有数中最小的;
考虑删除一个好数还是不好数:
删除一个好数,则总的好数数量将减少一个(因为删除它后能影响到的好数仅有它自己);
删除一个不好数,考虑删除这个不好数后能影响到的好数有几个,那么总的好数数量就减少几个;(被它所影响到的好数(假设目前考虑的好数是a[i])是那些满足 最小{a[0~1-i]}<a[i]<=次小{a[0~n-1]} 的数)
AC代码:
#include <iostream> #include<cstdio> #include<algorithm> typedef long long ll; #define inf 0x3f3f3f3f using namespace std; ll a[1000010]; ll first[1000010]; ll second[1000010]; bool flag[1000010]; ll cnt[1000010]; int main() { ll t; scanf("%lld",&t); while(t--){ ll n; scanf("%lld",&n); ll now_min=inf;ll pre_min=inf; for(ll i=1;i<=n;i++){ scanf("%lld",&a[i]); first[i]=now_min; second[i]=pre_min; //维护前缀最小和前缀次小 if(a[i]<=now_min) {pre_min=now_min; now_min=a[i];} else {if(a[i]<pre_min) pre_min=a[i];} } for(ll i=1;i<=n;i++){//不好数标记为1,好数标记为0 if(a[i]<=first[i]) flag[i]=1; else flag[i]=0; } ll k; for(ll i=1;i<=n;i++){ if(flag[i]==1){ k=i; cnt[k]=0; } else{ if(a[i]<=second[i]) cnt[k]++; } } ll ans=inf; for(ll i=1;i<=n;i++){ if(flag[i]==1&&cnt[i]==0) ans=min(ans,a[i]); } if(ans==inf) { for(ll i=1;i<=n;i++){ if(flag[i]==0) ans=min(ans,a[i]); else if(cnt[i]==1) ans=min(ans,a[i]); } } printf("%lld ",ans); } return 0; }
过了此题是真的开心~~~,要多思考啊