NC54477. Improvements
描述
输入描述
The first line of the input file contains n (1 ≤ n ≤ 200 000) — the number of ships. The following line contains n distinct integers xi (1 ≤ xi ≤ n) — the initial positions of the spaceships.
输出描述
The output file must contain one integer — the maximal number of ships that can remain at their initial positions in the solution of this problem.
示例1
输入:
4 1 3 2 4
输出:
3
说明:
In the first sample Son Halo can move the second spaceship in the position between the first and the third to solve the problem while keeping 3 other ships at their initial positions.示例2
输入:
4 1 4 2 3
输出:
4
说明:
In the second sample there are no rope intersections, so all 4 ships can be left at their initial positions.C++14(g++5.4) 解法, 执行用时: 38ms, 内存消耗: 5656K, 提交时间: 2020-10-12 20:10:14
#include<bits/stdc++.h> using namespace std; const int N=200010; int f[N],g[N],a[N]; int tf[N],tg[N],n; inline void add1(int x,int y){ while(x<=n)tf[x]=max(tf[x],y),x+=x&-x; } inline void add2(int x,int y){ while(x>=1)tg[x]=max(tg[x],y),x-=x&-x; } inline int query1(int x){ int ans=0; while(x>=1)ans=max(ans,tf[x]),x-=x&-x; return ans; } inline int query2(int x){ int ans=0; while(x<=n)ans=max(ans,tg[x]),x+=x&-x; return ans; } int main(){ scanf("%d",&n); for(int i=1;i<=n;++i)scanf("%d",&a[i]); int mx=0; for(int i=1;i<=n;++i){ f[i]=query1(a[i]-1)+1; g[i]=query2(a[i]+1)+1; add1(a[i],f[i]);add2(a[i],g[i]); mx=max(mx,f[i]+g[i]-1); } cout<<mx; return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 108ms, 内存消耗: 84628K, 提交时间: 2020-10-09 12:36:55
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define int ll const int N=1e7+10; const int inf=0x3f3f3f3f; int n,m,k; int a[N]; int f[N],g1[N],g2[N]; signed main(){ cin>>n; int x; for(int i=0;i<n;i++){ scanf("%d",&x);a[x-1]=i; } memset(f,inf,sizeof f); for (int i=0;i<n;i++) { int k=lower_bound(f,f+n,a[i])-f; f[k]=a[i];g1[i]=k+1; } reverse(a,a+n); memset(f,inf,sizeof f); for (int i=0;i<n;i++) { int k=lower_bound(f,f+n,a[i])-f; f[k]=a[i];g2[i]=k+1; } int mx=0; for (int i=0;i<n;i++){ mx=max(mx,g1[i]+g2[n-i-1]-1); } cout<<mx<<endl; return 0; }