【网络流24题】最长不下降子序列问题

题面

https://www.luogu.org/problemnew/show/P2766

我也不知道为什么全合肥八中(hfyz2018ji37)就我一个蒟蒻写了费用流。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#define N 1500
#define INF 1000000007
#define T (2*n+1)
#define S 0
#define LL long long
#define ri register int
using namespace std;

int n,a[N];
LL ans1,ans2;

struct graph {
  vector<int> to,w,c;
  vector<int> ed[N];
  LL dis[N]; int cur[N]; bool vis[N];
  void clear() {
    for (ri i=S;i<=T;i++) ed[i].clear();
    to.clear(); w.clear(); c.clear();
  }
  void add_edge(int a,int b,int aw,int ac) {
    to.push_back(b); w.push_back(aw); c.push_back(ac);  ed[a].push_back(to.size()-1);
    to.push_back(a); w.push_back(0);  c.push_back(-ac); ed[b].push_back(to.size()-1);
  }
  bool spfa() {
    memset(dis,-0x3f,sizeof(dis));
    memset(vis,0,sizeof(vis));
    queue<int> q;
    dis[S]=0;q.push(S);vis[S]=1;
    while (!q.empty()) {
      int x=q.front(); q.pop();
      for (ri i=0;i<ed[x].size();i++) {
        int e=ed[x][i];
        if (dis[to[e]]<dis[x]+c[e] && w[e]) {
          dis[to[e]]=dis[x]+c[e];
          if (!vis[to[e]]) vis[to[e]]=1,q.push(to[e]);
        }
      }
      vis[x]=0;
    }
    return dis[T]>-INF;
  }
  int dfs(int x,int lim) {
    if (x==T || !lim) return lim;
    LL sum=0; vis[x]=1;
    for (ri &i=cur[x];i<ed[x].size();i++) {
      int e=ed[x][i];
      if (dis[x]+c[e]==dis[to[e]] && w[e] && !vis[to[e]]) {
        int f=dfs(to[e],min(lim,w[e]));
        w[e]-=f; w[1^e]+=f;
        lim-=f; sum+=f;
        if (!lim) return sum;
      }
    }
    return sum;
  }
  void work() {
    spfa();
    ans1=dis[T];
    memset(vis,0,sizeof(vis));
    memset(cur,0,sizeof(cur));
    ans2=dfs(S,INF);
    while (spfa()) {
      memset(vis,0,sizeof(vis));
      memset(cur,0,sizeof(cur));
      int t=dfs(S,INF);
      if (dis[T]==ans1) ans2+=t;
    }
  }
  LL zkw(int s) {
    LL ret=0;
    while (spfa()) {
      memset(vis,0,sizeof(vis));
      memset(cur,0,sizeof(cur));
      int t=dfs(S,INF);
      if (dis[T]==s) ret+=t;
    }
    return ret;
  }
} G;

int main() {
  scanf("%d",&n);
  for (ri i=1;i<=n;i++) scanf("%d",&a[i]);
  for (ri i=1;i<=n;i++) {
    G.add_edge(S,i,INF,0);
    G.add_edge(i,n+i,1,1);
    G.add_edge(n+i,T,INF,0);
    for (ri j=i+1;j<=n;j++) if (a[i]<=a[j]) G.add_edge(n+i,j,INF,0);
  }
  G.work();
  cout<<ans1<<endl<<ans2<<endl;
  
  G.clear();
  for (ri i=1;i<=n;i++) {
    G.add_edge(S,i,INF,0);
    if (i==1 || i==n) G.add_edge(i,n+i,INF,1); else G.add_edge(i,n+i,1,1);
    G.add_edge(n+i,T,INF,0);
    for (ri j=i+1;j<=n;j++) if (a[i]<=a[j]) G.add_edge(n+i,j,1,0);
  }
  if (ans1==1) cout<<ans2<<endl; else cout<<G.zkw(ans1)<<endl;
}

 

posted @ 2019-07-13 22:57  HellPix  阅读(131)  评论(0编辑  收藏  举报