csuoj-1004-Xi and Bo
题目:
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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构