HDU 5356 sequence conversion

Ideas

This question is a modified version of the longest ascending subsequence. To ensure strict increase,
a [j] − a [i] >= j − ia[j]-a[i]>=jia[j]a[i]>=ji,化简得 a [ j ] − j > a [ i ] − i a[j]-j>a[i]-i a[j]j>a[i]i , so we only need to obtain the LIS of sequence b (b [i] = a [i] − ib[i]=a[i]-ib[i]=a[i]i ), but if you write it in dynamic programming, it will drop T. For LIS, you need to use the greedy + bisection solution. If you don’t understand, you can look atthe two complexity solutions of the longest ascending subsequence

Code
  • Use upper_bound() version
#pragma GCC optimize(2)
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
#define pi acos(-1.0)
#define e exp(1.0)
#define pb push_back
#define mk make_pair
#define fir first
#define sec second
#define scf scanf
#define prf printf
typedef pair<ll,ll> pa;
const ll INF=0x3f3f3f3f3f3f3f3f;
const ll MAX_T=12;
const ll MAX_N=1e5+7;
ll T,N;
ll A[MAX_N],B[MAX_N];
ll do_LIS(){
    
    
	ll i,j,k,cnt=0;
	for(i=0;i<N;i++){
    
    
		ll pos=upper_bound(B,B+cnt,A[i])-B;
		if(pos==cnt){
    
    
			cnt++;
		}
		B[pos]=A[i];
	}
	return cnt;
}
int main()
{
    
    
//  freopen(".../.txt","w",stdout);
//  freopen(".../.txt","r",stdin);
//	ios::sync_with_stdio(false);
	ll i,j,k=0;
	scf("%lld",&T);
	while(T--){
    
    
		scf("%lld",&N);
		for(i=0;i<N;i++){
    
    
			scf("%lld",&A[i]);
			A[i]-=i;
		}
		ll res=N-do_LIS();
		prf("Case #%lld:\n",++k);
		prf("%lld\n",res);
	}
	return 0;
}
  • This is a handwritten bisection version
#pragma GCC optimize(2)
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
#define pi acos(-1.0)
#define e exp(1.0)
#define pb push_back
#define mk make_pair
#define fir first
#define sec second
#define scf scanf
#define prf printf
typedef pair<ll,ll> pa;
const ll INF=0x3f3f3f3f3f3f3f3f;
const ll MAX_T=12;
const ll MAX_N=1e5+7;
ll T,N;
ll A[MAX_N],B[MAX_N];
ll do_LIS(){
    
    
	ll i,j,k,cnt=0;
	for(i=0;i<N;i++){
    
    
		ll L=0,R=cnt-1,mid,res=-1;
		while(L<=R){
    
    
			mid=L+(R-L)/2;
			if(B[mid]>A[i]){
    
    
				res=mid;
				R=mid-1;
			}
			else{
    
    
				L=mid+1;
			}
		}
		if(res==-1){
    
    
			B[cnt]=A[i];
			cnt++;
		}
		else
		B[res]=A[i];
	}
	return cnt;
}
int main()
{
    
    
//  freopen(".../.txt","w",stdout);
//  freopen(".../.txt","r",stdin);
//	ios::sync_with_stdio(false);
	ll i,j,k=0;
	scf("%lld",&T);
	while(T--){
    
    
		scf("%lld",&N);
		for(i=0;i<N;i++){
    
    
			scf("%lld",&A[i]);
			A[i]-=i;
		}
		ll res=N-do_LIS();
		prf("Case #%lld:\n",++k);
		prf("%lld\n",res);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43311695/article/details/108589632