【BZOJ】2208 [Jsoi2010]连通数

【题意】给定n个点的有向图,求可达点对数(互相可达算两对,含自身)。n<=2000。

【算法】强连通分量(tarjan)+拓扑排序+状态压缩(bitset)

【题解】这题可以说非常经典了。

1.强连通分量(scc)内所有点可互达,对答案的贡献为cnt[i]*cnt[i](cnt[i]第i个scc内点的个数)。

2.缩点得到新图,对新图中的每一个点开一个bitset[2000]来记录第i个点能否到达它,初始值为f[i][i]=1。

bitset用法:http://blog.163.com/lixiangqiu_9202/blog/static/53575037201251121331412/

(DAG和树不同,x到y会有多条路径,所以不能简单的记录数值而是要记录状态来合并,因为信息不可重,这里bitset的使用非常经典)

3.按拓扑序进行递推,f[y]|=f[x](edge x→y)

4.f[i][j]==1时ans+=cnt[i]*cnt[j]。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<bitset>
using namespace std;
const int maxn=2010,maxm=5000010;
struct edge{int u,v,from;}e[maxm],e1[maxm];
int n,tot,tot1,first[maxn],first1[maxn],dfn[maxn],low[maxn],mark,s[maxn],lack[maxn],color,col[maxn],num[maxn],top,in[maxn];
char st[2010];
bitset<maxn>f[maxn];
queue<int>q;
void insert(int u,int v)
{tot++;e[tot].u=u;e[tot].v=v;e[tot].from=first[u];first[u]=tot;}
void insert1(int u,int v)
{tot1++;e1[tot1].u=u;e1[tot1].v=v;e1[tot1].from=first1[u];first1[u]=tot1;in[v]++;}
void tarjan(int x)
{
    dfn[x]=low[x]=++mark;
    s[++top]=x;lack[x]=top;
    for(int i=first[x];i;i=e[i].from)
     {
         int y=e[i].v;
         if(!dfn[y])
          {
              tarjan(y);
              low[x]=min(low[x],low[y]);
          }
         else if(!col[y])low[x]=min(low[x],dfn[y]);
     }
    if(dfn[x]==low[x])
     {
         color++;
         for(int i=lack[x];i<=top;i++)col[s[i]]=color;
         num[color]=top-lack[x]+1;
         top=lack[x]-1;
     }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
     {
         scanf("%s",st);
         for(int j=0;j<n;j++)
          if(st[j]=='1')insert(i,j+1);
     }
    for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i);
    for(int i=1;i<=tot;i++)
     if(col[e[i].u]!=col[e[i].v])insert1(col[e[i].u],col[e[i].v]);
    for(int i=1;i<=color;i++)if(!in[i])q.push(i);
    for(int i=1;i<=color;i++)f[i][i]=1;
    while(!q.empty())
     {
         int x=q.front();q.pop();
         for(int i=first1[x];i;i=e1[i].from)
          {
              int y=e1[i].v;
              f[y]|=f[x];
              in[y]--;
              if(in[y]==0)q.push(y);
          }
     }
    long long ans=0;
    for(int i=1;i<=color;i++)
     for(int j=1;j<=color;j++)
      if(f[i][j])ans+=1ll*num[i]*num[j];
    printf("%lld",ans);
    return 0;
}
View Code

 

posted @ 2016-09-21 21:07  ONION_CYC  阅读(399)  评论(0编辑  收藏  举报