三校联考模拟(五) longseq最长子序列
程序员文章站
2022-06-02 12:33:12
...
二分答案。
二分x,x表示至少出现次数。
dfs代码:
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e3+100;
const int N=1<<8;
int a[maxn],dp[maxn][N];
int ans,n,inf;
vector<int>v[8];
int dfs(int i,int s ,int x){//位置,状态,个数
if(dp[i][s]!=inf) return dp[i][s];//记忆化
if(i>n){
if(s==N-1) return 0;//succeed
else return inf;//fail;
}
int ret=inf;
if(!(s&(1<<a[i]))){
int pos=lower_bound(v[a[i]].begin(),v[a[i]].end(),i)-v[a[i]].begin();
if(pos+x-1<v[a[i]].size()){
ret=max(ret,x+dfs(v[a[i]][pos+x-1]+1,s|(1<<a[i]),x));
}
if(pos+x<v[a[i]].size()){
ret=max(ret,x+1+dfs(v[a[i]][pos+x]+1,s|(1<<a[i]),x));
}
}
ret=max(ret,dfs(i+1,s,x));
return dp[i][s]=ret;//更新dp[i][s]
}
bool check(int mid){
memset(dp,-0x3f,sizeof dp);
inf=dp[0][0];
int tmp=dfs(1,0,mid);
ans=max(ans,tmp);
if(tmp>0)return 1;
return 0;
}
int main(){
freopen("longseq.in","r",stdin);
freopen("longseq.out","w",stdout);
scanf("%d",&n);
for(int i=0;i<8;i++)
v[i].clear();
int mark=0;
ans=0;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
a[i]--;
if(!(mark&(1<<a[i])))ans++,mark=mark|(1<<a[i]);
v[a[i]].push_back(i);
}
int l=1,r=n>>3;
while(l<=r){//二分x,个数
int mid=l+r>>1;
if(check(mid)) l=mid+1;
else r=mid-1;
}
printf("%d\n",ans);
return 0;
}
dp:
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int read()
{
int x=0,flag=0;
char ch=getchar();
if(ch=='-') flag=1;
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9')x*=10,x+=ch-'0',ch=getchar();
if(flag) return -x;
return x;
}
int write(int x)
{
if(x<0) putchar('-'),x=-x;
if(x>=10)write(x/10);
putchar(x%10+'0');
}
int n,ans=0,a[1100];
int f[1100][1100];
int num[1100];
vector <int> v[10];
int Clac(int x)
{
memset(f,-1,sizeof(f));
memset(num,0,sizeof(num));
f[0][0]=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<(1<<8);j++)
if(f[i][j]>-1)
{
for(int k=0;k<8;k++)
if((j&(1<<k))==0)
{
int l=x+num[k]-1;
if(l>=v[k].size()) continue;
f[v[k][l]+1][j|(1<<k)]=max(f[i][j],f[v[k][l]+1][j|(1<<k)]);
l++;
if(l>=v[k].size()) continue;
f[v[k][l]+1][j|(1<<k)]=max(f[i][j]+1,f[v[k][l]+1][j|(1<<k)]);
}
}
num[a[i+1]-1]++;
}
int res=-1;
for(int i=0;i<=n;i++)
res=max(res,f[i][(1<<8)-1]);
if(res==-1) return -1;
return x*8+res;
}
int main()
{
freopen("longseq.in","r",stdin);
freopen("longseq.out","w",stdout);
n=read();
for(int i=1;i<=n;i++)
a[i]=read(),v[a[i]-1].push_back(i-1);
for(int i=1;i<=n>>3;i++)
ans=max(ans,Clac(i));
if(!ans)
{
for(int i=0;i<8;i++)
if(v[i].size()) ans++;
}
write(ans);
fclose(stdin);
fclose(stdout);
return 0;
}
上一篇: 2018.7.26第二场T1题解