A-Angel Jelly

topic

There is a jelly lined up in a row. The deliciousness of the i-th jelly is that ai
angel likes to eat jelly very much, but she wants to save the best jelly for the last collection. The angel wants to know how delicious is the second most delicious jelly in the previous jelly?
There are a total of inquiries.
Note: If there are more than two largest numbers, the second largest is equal to the largest by default. For example, in this sequence, the second largest number is 4.

Insert picture description here

Link: https://ac.nowcoder.com/acm/contest/11161/A
Source: Niuke.com

enter

5
1 2 5 3 5
4
2
3
4
5

Output

1
2
3
5

Description

The first 2 numbers, the second largest is 1.
The first 3 numbers, the second largest is 2.
The first 4 numbers, the second largest is 3.
The first 5 numbers, the second largest is 5.


AC code

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define pre(i,a,b) for(int i=a;i>=b;--i)
#define m(x) memset(x,0,sizeof x)
const double PI = acos(-1);
const int maxn = 100005;
typedef long long ll;
int a[maxn],pre[maxn],p[maxn];
int main()
{
    
    
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        pre[0]=a[0];p[0]=0;
    
    
    
        for(int i=1;i<n;i++){
    
    
            pre[i]=max(a[i],pre[i-1]);
            if(pre[i]==a[i]){
    
    
                p[i]=pre[i-1];
            }
            else if(pre[i]==pre[i-1]){
    
    
                p[i]=max(a[i],p[i-1]);
            }
        }
    
    
        int t;
        scanf("%d",&t);
        while(t--){
    
    
            int x;
            scanf("%d",&x);
            printf("%d\n",p[x-1]);
        }
    
    return 0;
}


A little thought

This question depends on the range of data violence sort will definitely blow up. Therefore, the idea of ​​prefix sum is adopted;
pre[I] is used to store the largest number in the first i data, and then it is convenient to run, if a certain number in 1-x is less than pre[i] (not the largest) and greater than The previous pre is the second largest

Guess you like

Origin blog.csdn.net/DAVID3A/article/details/115016829