【BZOJ】2208 [Jsoi2010]連通數

來源:互聯網
上載者:User

標籤:

【演算法】強連通分量(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/

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

 

【BZOJ】2208 [Jsoi2010]連通數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.