[简单思维题]Sequence(山东省第九届ACM大学生程序设计竞赛E题)

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(1j<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(1T103).
For each test case, the first line contains an integer n(1\le n\le 10^6)n(1n106), 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(1pin), representing  the given permutation pp.
It’s guaranteed that \sum n\le 2\times 10^7n2×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\n",ans);
    }
    return 0;
}

过了此题是真的开心~~~,要多思考啊

转载于:https://www.cnblogs.com/lllxq/p/9038698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值