J Mex 牛客

链接:https://ac.nowcoder.com/acm/contest/700/J
来源:牛客网
 

题目描述

Recently MINIEYE's engineer M is working on neural network model training and he has found that if the output of the network is S = (S1, S2, …, Sn), then we can use mex(S) to predict the total training time of the neural network. Define mex(S) as:

Here S' ≤ S means S' is a subsequence of S, ∑S' represents the sum of all elements in S'. Please note that S' can be empty, and in that case ∑S' is 0.

M needs your help to calculate mex(S).

输入描述:

 

The first line contains a single integer n(1 ≤ n ≤ 105).

The second line contains n non-negative integers Si(0 ≤ Si < 231).

输出描述:

Print mex(S) in a single line.

示例1

输入

复制

3
1 2 5

输出

复制

4

说明

S'=(), ∑S'=0

S'=(1), ∑S'=1

S'=(2), ∑S'=2

S'=(1,2), ∑S'=3

S'=(5), ∑S'=5

There
is no way for ∑S'=4, hence 4 is the answer.
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
const int maxx=1e5+10;
#define ll long long
ll a[maxn];
ll sum;
ll s=0;

int main(){
    ll n;
    cin>>n;
    if(n==0){cout<<1<<endl; return 0;}
    for(ll i=1;i<=n;i++){
        cin>>a[i];
        s=s+a[i];
    }
    sort(a+1,a+n+1);

    ll k=1;
    while(a[k]==0){ //k为第一个不为0 的数
        k++;
    }
    if(a[k]!=1){
        cout<<1<<endl;
        return 0;
    }
    if(n==k&&a[k]!=1){
        cout<<1<<endl;
        return 0;
    }
    sum=a[k];

    for(ll i=k+1;i<=n;++i){
        if(a[i]-a[i-1]==1||a[i]==a[i-1]){
            sum=sum+a[i];
            k=i;
        }else{
            break;
        }
    }
    //cout<<"k:"<<k<<endl;
    if(k==n||a[k+1]>sum+1){
        cout<<sum+1<<endl;
        return 0;
    }
    for(ll i=k+1;i<=n;i++)
    {
        //cout<<"sum:"<<sum<<endl;
        if(a[i]-a[i-1]>sum+1){
            cout<<a[i-1]+sum+1<<endl;
            //cout<<"i:"<<i-1<<endl;
            return 0;
        }else{
            if(i!=k+1)
                sum=sum+a[i-1];
        }
    }
    //cout<<"s:"<<s+1<<endl;
    cout<<s+1<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/The_Architect/article/details/89431972
Mex