题目:
Description
Bo has been in Changsha for four years. However he spends most of his time staying his small dormitory. One day he decides to get out of the dormitory and see the beautiful city. So he asks to Xi to know whether he can get to another bus station from a bus station. Xi is not a good man because he doesn‘t tell Bo directly. He tells to Bo about some buses‘ routes. Now Bo turns to you and he hopes you to tell him whether he can get to another bus station from a bus station directly according to the Xi‘s information.
Input
The first line of the input contains a single integer T
(0<T
<30) which is the number of test cases. For each test case, the first contains two different numbers representing the starting station and the ending station that Bo asks. The second line is the number n
(0<n
<=50) of buses‘ routes which Xi tells. For each of the following n lines, the first number m
(2<=m
<= 100) which stands for the number of bus station in the bus‘ route. The remaining m
numbers represents the m
bus station. All of the bus stations are represented by a number, which is between 0 and 100.So you can think that there are only 100 bus stations in Changsha.
Output
For each test case, output the "Yes
" if Bo can get to the ending station from the starting station by taking some of buses which Xi tells. Otherwise output "No
". One line per each case. Quotes should not be included.
Sample Input
3 0 3 3 3 1 2 3 3 4 5 6 3 1 5 6 0 4 2 3 0 2 3 2 2 4 3 2 1 4 2 1 0 3
Sample Output
No Yes Yes 分析:1,初始化,每个节点单独作为一个集合,集合的代表元素为该节点;2,求出每条公交路线第一个站点的祖父,即其所在集合的代表元;3,求出该路线上的其他节点的祖父,将其父节点设置为步骤2中的代表元,即合并原本不相交的两个集合;4,根据祖父节点即所在集合的代表元是否相同来判断查询的两个公交站是否属于同一个集合。 代码:
#include<iostream> using namespace std; int node[101]; int findRoot(int temp){ int root = node[temp]; while(root != temp){ temp = root; root = node[temp]; }//while return root; } int main(){ int t; cin >> t; while(t--){ for(int i = 0;i <= 100;i++){ node[i] = i; }//for int begin,end; cin >>begin >>end; int cnt; cin >>cnt; for(int i = 0;i < cnt;i++){ int num; cin >>num; int first; cin >>first; int root = findRoot(first); for(int j = 1;j < num;j++){ int temp; cin >>temp; int tempRoot = findRoot(temp); node[tempRoot] = root; }//for }//for int beginRoot = findRoot(begin); int endRoot = findRoot(end); if(beginRoot == endRoot) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }