由于要使点最多,所以同一个强连通分量中的点要么都选,要么都不选。然后tarjan缩点,新点的权值为该强连通分量中点的个数。然后在新的DAG上求一条最长的链并统计最长链的个数即可。记忆化搜索解决(当然也可以bfs顺推然而我懒-_-。
下附AC代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define N 100005 #define M 1000005 using namespace std; int n,m,mod,tot,cnt,fst[N],pnt[M],nxt[M]; int dfsclk,tp,stk[N],pos[N],low[N],scc[N],sum[N],f[N],g[N]; bool bo[N]; struct edg{ int x,y; }a[M]; bool cmp(edg aa,edg bb){ return aa.x<bb.x || (aa.x==bb.x && aa.y<bb.y); } int read(){ int x=0; char ch=getchar(); while (ch<'0' || ch>'9') ch=getchar(); while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); } return x; } void add(int aa,int bb){ pnt[++tot]=bb; nxt[tot]=fst[aa]; fst[aa]=tot; } void dfs(int x){ pos[x]=low[x]=++dfsclk; int p; stk[++tp]=x; for (p=fst[x]; p; p=nxt[p]){ int y=pnt[p]; if (!pos[y]){ dfs(y); low[x]=min(low[x],low[y]); } else if (!scc[y]) low[x]=min(low[x],pos[y]); } if (low[x]==pos[x]){ cnt++; scc[x]=cnt; for (sum[cnt]=1; stk[tp]!=x; tp--){ scc[stk[tp]]=cnt; sum[cnt]++; } tp--; } } void dp(int x){ if (f[x]) return; int p; for (p=fst[x]; p; p=nxt[p]){ int y=pnt[p]; dp(y); if (f[y]>f[x]){ f[x]=f[y]; g[x]=g[y]; } else if (f[y]==f[x]) g[x]=(g[x]+g[y])%mod; } if (!f[x]) g[x]=1; f[x]+=sum[x]; } int main(){ n=read(); m=read(); mod=read(); int i,p; for (i=1; i<=m; i++){ int x=read(),y=read(); add(x,y); } for (i=1; i<=n; i++) if (!pos[i]) dfs(i); m=0; for (i=1; i<=n; i++) for (p=fst[i]; p; p=nxt[p]){ int j=pnt[p]; if (scc[i]!=scc[j]){ m++; a[m].x=scc[i]; a[m].y=scc[j]; } } sort(a+1,a+m+1,cmp); tot=0; memset(fst,0,sizeof(fst)); for (i=1; i<=m; i++) if (i==1 || a[i].x!=a[i-1].x || a[i].y!=a[i-1].y){ add(a[i].x,a[i].y); bo[a[i].y]=1; } for (i=1; i<=cnt; i++) if (!bo[i]) add(0,i); dp(0); printf("%d\n%d\n",f[0],g[0]); return 0; }
2015.12.4