已知一个长度为n的排列,先求出它的最长上升子序列的长度,设为k,再求长度为k的上升子序列有多少个。每个点只能经过一次。
自认为这道题比较像最短路计数。类似的,先求出最长上升子序列(O(n^2)都可以),然后把每个点拆点,容量为1,因为只能走一次。源点s连向dp[i]=1的点,dp[i]=k的点连向汇点t,当dp[i]=dp[j]+1且a[j]<a[i]时j向i连容量为1的边,该图的最大流就是长度为k的上升子序列个数。本题有坑的地方,没有给出n的范围,而且k有可能等于i。
#include<cstdio>
#include<cstring>
#include<vector>
#define MAXN 10010
using namespace std;
inline int Min(int a,int b)
{return a<b?a:b;}
inline int Max(int a,int b)
{return a>b?a:b;}
struct E
{
int v,w,op;
E(){}
E(int a,int b,int c)
{v = a; w = b; op = c;}
};
vector<E> g[100010];
int d[MAXN],vd[MAXN],dp[MAXN],n,k,s,t,flow,a[MAXN];
void get_dp()
{
dp[1] = 1,k = 0;
for(int i = 2; i <= n; i++)
{
dp[i] = 1;
for(int j = 1; j < i; j++)
{
if(a[j]<a[i]) dp[i] = Max(dp[i],dp[j]+1);
}
if(dp[i] > k) k = dp[i];
}
}
void build()
{
for(int i = 1; i <= n; i++)
{
g[i].push_back(E(i+n,1,g[i+n].size()));
g[i+n].push_back(E(i,0,g[i].size()-1));
if(dp[i] == 1)
{
g[s].push_back(E(i,1,g[i].size()));
g[i].push_back(E(s,0,g[s].size()-1));
}
if(dp[i] == k)//数据貌似有点坑,k应该有等于1的情况,多加了个else就WA了
{
g[i+n].push_back(E(t,1,g[t].size()));
g[t].push_back(E(i+n,0,g[i+n].size()-1));
}
for(int j = 1; j < i; j++)
if(dp[i] == dp[j]+1&&a[i] > a[j])
{
g[j+n].push_back(E(i,1,g[i].size()));
g[i].push_back(E(j+n,0,g[j+n].size()-1));
}
}
}
int aug(int i,int augco)
{
int j,augc = augco,mind = t-1,delta,sz = g[i].size();
if(i == t) return augco;
for(j = 0; j < sz; j++)
{
int v = g[i][j].v;
if(g[i][j].w)
{
if(d[i] == d[v]+1)
{
delta = Min(augc,g[i][j].w);
delta = aug(v,delta);
g[i][j].w -= delta;
g[v][g[i][j].op].w += delta;
augc -= delta;
if(d[s] >= t) return augco - augc;
if(augc == 0) break;
}
if(d[v] < mind) mind = d[v];
}
}
if(augc == augco)
{
vd[d[i]]--;
if(vd[d[i]] == 0) d[s] = t;
d[i] = mind+1;
vd[d[i]]++;
}
return augco - augc;
}
void sap()
{
flow = 0;
memset(d,0,sizeof d);
memset(vd,0,sizeof vd);
while(d[s] < t)
flow += aug(s,0x3f3f3f3f);
}
int main()
{
while(scanf("%d",&n) != EOF)
{
memset(dp,0,sizeof dp);
memset(a,0,sizeof a);
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
s = 2*n+1,t = s+1;
get_dp();
build();
sap();
printf("%d\n%d\n",k,flow);
for(int i = 1; i <= t; i++)
g[i].clear();
}
}