输入数据第一行是图顶点的数量,一个正整数N。 接下来N行,每行N个字符。第i行第j列的1表示顶点i到j有边,0则表示无边。
输出一行一个整数,表示该图的连通数。
对于100%的数据,N不超过2000。
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cmath> 4 #include<cstring> 5 #include<algorithm> 6 #include<iostream> 7 #include<vector> 8 #include<map> 9 #include<set> 10 #include<queue> 11 #define inf 1000000000 12 #define maxn 2000+100 13 #define maxm 4000000+1000 14 #define eps 1e-10 15 #define ll long long 16 using namespace std; 17 int n,ans,tot,head[maxn],next[maxm],go[maxm]; 18 bool v[maxn]; 19 inline int read() 20 { 21 int x=0,f=1;char ch=getchar(); 22 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} 23 while(ch>=‘0‘&&ch<=‘9‘){x=10*x+ch-‘0‘;ch=getchar();} 24 return x*f; 25 } 26 inline void dfs(int x) 27 { 28 v[x]=1;ans++; 29 for(int i=head[x];i;i=next[i])if(!v[go[i]])dfs(go[i]); 30 } 31 int main() 32 { 33 freopen("input.txt","r",stdin); 34 freopen("output.txt","w",stdout); 35 n=read();char ch; 36 for(int i=1;i<=n;i++) 37 { 38 for(int j=1;j<=n;j++) 39 { 40 ch=‘ ‘;while(ch<‘0‘||ch>‘1‘)ch=getchar(); 41 if(ch==‘1‘) 42 { 43 go[++tot]=j;next[tot]=head[i];head[i]=tot; 44 } 45 } 46 } 47 ans=0; 48 for(int i=1;i<=n;i++) 49 { 50 memset(v,0,sizeof(v)); 51 dfs(i); 52 } 53 printf("%d\n",ans); 54 }
BZOJ2208: [Jsoi2010]连通数,布布扣,bubuko.com
原文:http://www.cnblogs.com/zyfzyf/p/3926896.html