网络流的题还是做过一些的,但是今天这一道我并不是很会。
第一问很明显,直接暴力,n^2直接得出答案。第二问和第三问我想了有很久
st是源点,ed是汇点
首先题目上告诉我们只允许使用一次就明摆着可能要拆点,那么的话建边大概就是<st,i1>,<i1,i2>,<i2,ed>,<i2,j1>了。但是我有一点弄不清楚,如何保证最后在ed中的答案是最长不下降子序列呢?
没出息的RenLine_去看了一眼题解
其实也没那么难,所有点我们都能知道它在最长不下降子序列中是第几个,只有满足j>i&&aj>=ai&&fj==fi+1才去建边<i2,j1>就好了
毕竟我们只是在所有的最长不下降子序列中筛选“最大流而已,只要最后数量是最多的就好。
下面是我的代码,很丑,见谅:
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 1100
using namespace std;
struct node{int x,y,c,next;}p[maxn*600];
int f[maxn],h[maxn],n,m,maxflow,st,ed,a[maxn],ans,last[maxn],len;
void ins(int x,int y,int c)
{
len++;
p[len].x=x;p[len].y=y;p[len].c=c;
p[len].next=last[x];last[x]=len;
}
bool bfs()
{
memset(h,0,sizeof(h));h[st]=1;
queue<int>q;q.push(st);
while(!q.empty())
{
int x=q.front();q.pop();
for(int k=last[x];k;k=p[k].next)
{
int y=p[k].y;
if(!h[y]&&p[k].c>0)
{
h[y]=h[x]+1;
q.push(y);
}
}
}
return h[ed]!=0;
}
int flow(int x,int w)
{
if(x==ed)return w;
int f=0;
for(int k=last[x];k;k=p[k].next)
{
int y=p[k].y;
if(h[y]==h[x]+1&&p[k].c>0&&f<w)
{
int ft=flow(y,min(p[k].c,w-f));
f+=ft;p[k].c-=ft;
int other=k+1;
if(k%2)other=k-1;
p[other].c+=ft;
}
}
if(!f)h[x]=0;
return f;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)f[i]=1;
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
if(n==1){printf("1\n1\n1");return 0;}
for(int i=1;i<=n;i++)for(int j=1;j<i;j++)if(a[i]>=a[j])f[i]=max(f[i],f[j]+1);
for(int i=1;i<=n;i++)ans=max(ans,f[i]);
printf("%d\n",ans);
st=n+n+1;ed=st+1;
for(int i=1;i<=n;i++)
{
if(f[i]==1){ins(st,i,1);ins(i,st,0);}
ins(i,i+n,1);ins(i+n,i,0);
if(f[i]==ans){ins(i+n,ed,1);ins(ed,i+n,0);}
for(int j=i+1;j<=n;j++)if(f[i]+1==f[j]&&a[j]>=a[i]){ins(i+n,j,1);ins(j,i+n,0);}
}//建边
while(bfs())maxflow+=flow(st,1e9);//第二问结果
printf("%d\n",maxflow);
if(f[1]==1){ins(st,1,1e9);ins(1,st,0);}
ins(1,n+1,1e9);ins(n+1,1,0);
if(f[n]==ans){ins(n*2,ed,1e9);ins(ed,n*2,0);}
ins(n,n*2,1e9);ins(n*2,n,0);
while(bfs())maxflow+=flow(st,1e9);//再流一次就是第三问结果了
printf("%d",maxflow);
return 0;
}