[CF977F]Consecutive Subsequence

kDuiEq.md.jpg

题目描述

You are given an integer array of length n.

You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to [x,x+1,…,x+k−1] for some value x and length k.

Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array [5,3,1,2,4] the following arrays are subsequences: [3], [5,3,1,2,4], [5,1,4], but the array [1,3] is not.

题目大意

给你n个数的序列,求出最长的连续上升子序列(每个元素之间只差\(1\)),并输出在原序列中的位置。

40分做法

非常容易想到的暴力,我们开\(200000\)\(vector\),每次在已有的数组中找是否有一个数组的最后一个元素是当前数-1,如果有那么就插入到长度最长的一个,如果没有,那么就新开一个数组来存储新的数列。

40分代码

#include<bits/stdc++.h>
#define LL long long
#define pb push_back
using namespace std;
struct node{int x,p;};
vector<node>ans[200005];//其实可以用vector套vector
int cnt=0,n,len[200005],ret=0,res=0;
LL a[200005];
LL r(){LL x=0,w=0;char ch=0;while(!isdigit(ch))w|=ch=='-',ch=getchar();while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();return w?-x:x;}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++)a[i]=r();
    for(int i=1;i<=n;i++){
        int pos=-1;
        for(int j=1;j<=cnt;j++)if(ans[j][ans[j].size()-1].x==a[i]-1&&(pos==-1||ans[pos].size()<=ans[j].size()))pos=j;//找到已有的数组,在插入
        if(pos==-1)ans[++cnt].pb((node){a[i],i}); else ans[pos].pb((node){a[i],i});//如果没有合法的数组就新开一个。
    }
    for(int i=1;i<=cnt;i++)if(ret<ans[i].size())ret=ans[i].size(),res=i;
    printf("%d\n",ret); for(int i=0;i<ans[res].size();i++)printf("%d ",ans[res][i].p);
    return 0;
}

100分做法

其实是非常简单的DP问题,我们用\(F[i]\)表示以\(i\)为结尾的最长的序列,那么转移方程就是:\(F[i]=F[i-1]+1\)

但是这里的\(F\)数组的下标非常大,那么我们就用\(map\)来映射就可以了。

100分代码

#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define N 200005
using namespace std;
int a[N],n;
map<int,int>f;
int r(){int w=0,x=0;char ch=0;while(!isdigit(ch))w|=ch=='-',ch=getchar();while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();return w?-x:x;}
int main(){
    int cas=r();n=r();
    int x=0,Max=0;
    for(int i=1;i<=n;i++){
        a[i]=r();f[a[i]]=f[a[i]-1]+1;
        if(f[a[i]]>Max)Max=f[a[i]],x=a[i];
    }
    int t=x-Max+1;printf("%d\n",Max);
    for(int i=1;i<=n;i++)if(a[i]==t){printf("%d ",i);t++;}
    return 0;
}

转载于:https://www.cnblogs.com/chhokmah/p/10375447.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值