【BZOJ2208】【JSOI2010】连通数 传递闭包

题目描述

  定义一个图的连通度为图中可达顶点对的数目。给你一个\(n\)个点的有向图,问你这个图的连通度。

  \(n\leq 2000,m\leq n^2\)

题解

  一个很简单的做法就是传递闭包:像floyd算法一样处理两个点之间是否可达。

\[f_{i,j}|=f_{i,k}\&f_{k,j} \]

  但是这是\(O(n^3)\)的。

  观察到用到的运算都是位运算,那就用bitset加速一下就行了。

  时间复杂度:\(O(\frac{n^3}{64})\)(还是\(O(n^3)\)

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<ctime>
#include<utility>
#include<cmath>
#include<functional>
#include<bitset>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
void sort(int &a,int &b)
{
	if(a>b)
		swap(a,b);
}
void open(const char *s)
{
#ifndef ONLINE_JUDGE
	char str[100];
	sprintf(str,"%s.in",s);
	freopen(str,"r",stdin);
	sprintf(str,"%s.out",s);
	freopen(str,"w",stdout);
#endif
}
int rd()
{
	int s=0,c;
	while((c=getchar())<'0'||c>'9');
	do
	{
		s=s*10+c-'0';
	}
	while((c=getchar())>='0'&&c<='9');
	return s;
}
int upmin(int &a,int b)
{
	if(b<a)
	{
		a=b;
		return 1;
	}
	return 0;
}
int upmax(int &a,int b)
{
	if(b>a)
	{
		a=b;
		return 1;
	}
	return 0;
}
bitset<2001> f[2010];
char s[2010];
int main()
{
	int n;
	int i,j;
	scanf("%d",&n);
	for(i=1;i<=n;i++)
	{
		scanf("%s",s+1);
		for(j=1;j<=n;j++)
			if(s[j]-'0')
				f[i].set(j);
		f[i].set(i);
	}
	for(j=1;j<=n;j++)
		for(i=1;i<=n;i++)
			if(i!=j&&f[i][j])
				f[i]|=f[j];
	int s=0;
	for(i=1;i<=n;i++)
		s+=f[i].count();
	printf("%d\n",s);
	return 0;
}
posted @ 2018-03-06 11:00  ywwyww  阅读(152)  评论(0编辑  收藏  举报