bzoj1093 最大半连通子图 强连通分量&记忆化搜索

       由于要使点最多,所以同一个强连通分量中的点要么都选,要么都不选。然后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;
}

by lych

2015.12.4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值