题意:求最长上升子序列的长度和数量。
分析:用dp求出最长上升子序列m,dp数组存的就是该元素为子序列结尾的长度,源点与长度为1的点建边,长度为m的与汇点连边,然后枚举任意两个元素,ai,aj(ai>aj&&i>j&&dp[i]==dp[j]+1),j跟i连边,因为每个点只能选一次,所以边的容量都为1,求出最大流。
#include<stdio.h> #include<string.h> const int N=500; const int inf=0x3fffffff; int dis[N],gap[N],start,end,ans,dp[N],head[N],num; struct edge { int st,ed,flow,next; }e[N*5]; void addedge(int x,int y,int w) { e[num].st=x;e[num].ed=y;e[num].flow=w;e[num].next=head[x];head[x]=num++; e[num].st=y;e[num].ed=x;e[num].flow=0;e[num].next=head[y];head[y]=num++; } int dfs(int u,int minflow) { if(u==end)return minflow; int i,v,f,min_dis=ans-1,flow=0; for(i=head[u];i!=-1;i=e[i].next) { v=e[i].ed; if(e[i].flow<=0)continue; if(dis[v]+1==dis[u]) { f=dfs(v,e[i].flow>minflow-flow?minflow-flow:e[i].flow); e[i].flow-=f; e[i^1].flow+=f; flow+=f; if(flow==minflow)break; if(dis[start]>=ans)return flow; } min_dis=min_dis>dis[v]?dis[v]:min_dis; } if(flow==0) { if(--gap[dis[u]]==0) dis[start]=ans; dis[u]=min_dis+1; gap[dis[u]]++; } return flow; } int isap() { int maxflow=0; memset(gap,0,sizeof(gap)); memset(dis,0,sizeof(dis)); gap[0]=ans; while(dis[start]<ans) maxflow+=dfs(start,inf); return maxflow; } int main() { int i,j,n,a[N],cot; while(scanf("%d",&n)!=-1) { cot=0;start=0;end=n+1;ans=end+1;num=0; memset(head,-1,sizeof(head)); for(i=1;i<=n;i++) { scanf("%d",&a[i]); dp[i]=1; for(j=1;j<i;j++) {if(a[i]>a[j]&&dp[i]<=dp[j]) dp[i]=dp[j]+1;} if(cot<dp[i])cot=dp[i]; } printf("%d ",cot); for(i=1;i<=n;i++) { if(dp[i]==1) addedge(start,i,1); if(dp[i]==cot) addedge(i,end,1); addedge(i,i,1); } for(i=1;i<=n;i++) { for(j=1;j<i;j++) if(a[j]<a[i]&&dp[j]+1==dp[i]) addedge(j,i,1); } printf("%d ",isap()); } return 0; }