您的位置:首页 > 其它

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

2015-12-04 19:56 453 查看
由于要使点最多,所以同一个强连通分量中的点要么都选,要么都不选。然后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
,pnt[M],nxt[M];
int dfsclk,tp,stk
,pos
,low
,scc
,sum
,f
,g
;
bool bo
;
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: