BZOJ2208 [Jsoi2010]连通数

题目描述:

度量一个有向图连通情况的一个指标是连通,指途中可达点对的个数。

下图的连通数是14

现在要你求出连通数

n<=2000

题解:

网上的题解有的写得很复杂,但是看到n的范围这么小,当然会想到搜索算法。

所以考虑用bfs。

直接暴力地搜出每个点的连通数,最后统计一下答案即可。

注意不要忘了加上自己。

附上代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
int n,a[2001][2001],top1,cnt[2001],top2;
long long ans;
char s[2001];
bool vis[2001];
void bfs(int p)
{
    queue <int> q ;
    memset(vis,0,sizeof(vis)) ;
    q.push(p) ;
    vis[p]=1 ;
    while(!q.empty())
    {
        int x=q.front();
        q.pop() ;
        for (int i=1;i<=cnt[x];i++)
        if (!vis[a[x][i]])
        {
            ans++ ;
            vis[a[x][i]]=1 ;
            q.push(a[x][i]) ;
        }
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%s",s);
        int p=strlen(s);
        for(int j=0;j<p;j++)
            if(s[j]=='1')
            {
                cnt[i]++;
                a[i][cnt[i]]=j+1;
            }
    }
    for(int i=1;i<=n;i++)
        bfs(i);
    printf("%lld",ans+n);
}

另外此题的做法有:

做法1:tarjan缩点+拓扑

做法2:floyd传递闭包

做法3:暴力dfs

原文地址:https://www.cnblogs.com/jiangminghong/p/9817093.html