萌新求助网络流84pts

P2766 最长不下降子序列问题

Tyyyyyy @ 2022-02-10 20:33:44

rt,wa on test #11,#13。数据下下来是乱码。

#include<bits/stdc++.h>
using namespace std;
const int N=510,INF=2e9;
int n,a[N],dp[N],ans1;
int tot=1,h[N];
struct edge
{
    int v,w,nxt;
}e[N*N*4];
void add(int u,int v,int w)
{
    e[++tot]=(edge){v,w,h[u]};
    h[u]=tot;
}
int s,t,d[N];
bool bfs()
{
    memset(d,0,sizeof(d));
    queue<int>q;
    q.push(s),d[s]=1;
    while(!q.empty())
    {
        int u=q.front();q.pop();
        for(int i=h[u];i;i=e[i].nxt)
        {
            int v=e[i].v;
            if(e[i].w&&!d[v])
            {
                d[v]=d[u]+1,q.push(v);
                if(v==t)return 1;
            }
        }
    }
    return 0;
}
int dinic(int u,int flow)
{
    if(u==t)return flow;
    int rest=flow,k;
    for(int i=h[u];i&&rest;i=e[i].nxt)
    {
        int v=e[i].v;
        if(e[i].w&&d[v]==d[u]+1)
        {
            k=dinic(v,min(rest,e[i].w));
            if(!k)d[v]=0;
            rest-=k,e[i].w-=k,e[i^1].w+=k;
        }
    }
    return flow-rest;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]),dp[i]=1;
        for(int j=1;j<i;j++)
            if(a[j]<=a[i])dp[i]=max(dp[i],dp[j]+1);
        ans1=max(ans1,dp[i]);
    }
    printf("%d\n",ans1);
    if(ans1==1)
    {
        printf("%d\n",n);
        sort(a+1,a+n+1),n=unique(a+1,a+n+1)-a-1;
        printf("%d",n);
        return 0;
    }
    s=0,t=2*n+1;
    for(int i=1;i<=n;i++)add(i,i+n,1),add(i+n,i,0);
    for(int i=1;i<=n;i++)
    {
        if(dp[i]==1)add(s,i,INF),add(i,s,0);
        if(dp[i]==ans1)add(i+n,t,INF),add(t,i+n,0);
        for(int j=i+1;j<=n;j++)
            if(a[i]<=a[j]&&dp[i]+1==dp[j])add(i+n,j,1),add(j,i+n,0);
    }
    int flow,ans2=0;
    while(bfs())
        while(flow=dinic(s,INF))ans2+=flow;
    printf("%d\n",ans2);
    add(s,1,INF),add(1,s,0),add(1,n+1,INF),add(n+1,1,0);
    if(dp[n]==ans1)add(n+n,t,INF),add(t,n+n,0),add(n,n+n,INF),add(n+n,n,0);
    while(bfs())
        while(flow=dinic(s,INF))ans2+=flow;
    printf("%d",ans2);
    return 0;
}

by GR_mihro @ 2022-02-10 20:37:50

命运,倒映水中


by tofucurd @ 2022-02-10 20:51:30

重构


by grass8cow @ 2022-02-10 21:07:16

《萌新》


|