标签:uva
Graph Connectivity
Graph Connectivity |
Consider a graph G formed from a large number of nodes connected by edges. G is said to be connected if a path can be found in 0 or more steps between any pair of nodes in G. For example, the graph below is not connected because there is no path from A to C.
This graph contains, however, a number of subgraphs that are connected, one for each of the following sets of nodes: {A}, {B}, {C}, {D}, {E}, {A,B}, {B,D}, {C,E}, {A,B,D}
A connected subgraph is maximal if there are no nodes and edges in the original graph that could be added to the subgraph and still leave it connected. There are two maximal connected subgraphs above, one associated with the nodes {A, B, D} and the other with the nodes {C, E}.
Write a program to determine the number of maximal connected subgraphs of a given graph.
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
The first line of each input set contains a single uppercase alphabetic character. This character represents the largest node name in the graph. Each successive line contains a pair of uppercase alphabetic characters denoting an edge in the graph. The sample input section contains a possible input set for the graph pictured above.
Input is terminated by a blank line.
For each test case, the output the number of maximal connected subgraphs. The outputs of two consecutive cases will be separated by a blank line.
1 E AB CE DB EC
2
题目大意:
求子集的个数。
解题思路:
并查集。
代码:
#include<iostream> #include<cstdio> using namespace std; const int maxn=30; int t=0,temp,parent[maxn]; bool visited[maxn]; void initial(){ for(int i=0;i<=maxn;i++)parent[i]=i; for(int i=0;i<=maxn;i++)visited[i]=false; } int getRoot(int k){ if(k!=parent[k]) parent[k]=getRoot(parent[k]); return parent[k]; } void Union(int a,int b){parent[a]=b;} void solve(){ char ch[3]; gets(ch); temp=ch[0]-'A'+1; while(gets(ch)){ if(!ch[0]) break;//判断是否是空行 int p=getRoot(ch[0]-'A'+1),q=getRoot(ch[1]-'A'+1); if(p!=q) Union(p,q); } } void output(){ int cnt=0; for(int i=1;i<=temp;i++){ if(!visited[getRoot(i)]){ cnt++; visited[getRoot(i)]=true; } } printf("%d\n",cnt); if(t) printf("\n"); } int main(){ while(cin>>t){//原来大的测试也是多组的 getchar(); getchar(); while(t--){ initial(); solve(); output(); } } return 0; }
Graph Connectivity UVA, 459(并查集)
标签:uva
原文地址:http://blog.csdn.net/hush_lei/article/details/41171987