P2256 一中校运会之百米跑
-----------------------
题目链接:MIKU
---------------------
我现在发现找BUG的最好方法————喝水
喝一次找一个,喝两次A道题
---------------------------
好,下面来分析这道题,这道题一看,大家一定就会想到并查集
(不知道并查集是什么?)请自行百度或者是看博客:(链接指向网址未完工)
但是,并查集我们是针对数的,而这道题都是字符串,怎么办呢?就是建立一个结构体来储存名字和编号,当然,这样在查询时就必须要遍历每一个数组才能拿到编号,不过对于这套题来说,复杂度足够了。
所以说这道题还是挺模板的
或许MAP对于这道题也可以用,但是对于像我这样的蒟蒻来说,这种结构体还是比较稳定的;
(或许可以用一个<string,string>的MAP?,我没试)
---------------------------
再说一句,这道题的数据很水,写的是20000但是我开了个10000的数组就够了】
---------------------------
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 3 我现在发现了怎样A题 4 5 喝一口水找出一个bug 6 7 啊啊啊啊 8 9 */ 10 #include<iostream> 11 #include<cstdio> 12 #include<cstring> 13 #include<algorithm> 14 using namespace std; 15 struct com{ 16 int no; 17 string name; 18 } fa[10000];//受题目影响,就用了结构体 19 //用结构体打包 20 int faa[10000];//并查集部分 21 int n,m,k; 22 //得到名字,但是我们的并查集是要处理编号,所以说我们就要 23 //遍历得到编号 24 int find(string x){ 25 for(int i=1;i<=n+1;++i) 26 if(fa[i].name==x) 27 return fa[i].no; 28 } 29 int findd(int x)//并查集部分 30 { 31 if(faa[x]==x) 32 return x; 33 else 34 return faa[x]=findd(faa[x]); 35 } 36 37 string s,s1; 38 int main() 39 { 40 cin>>n>>m;//读入部分 41 for(int i=1;i<=n;++i) 42 { 43 cin>>s; 44 fa[i].no=i; 45 fa[i].name=s;//记录名字与编号 46 faa[i]=i;//并查集部分 47 } 48 for(int i=1;i<=m;++i) 49 { 50 cin>>s>>s1; 51 int v1=find(s); 52 int v2=find(s1);//将我们得到的名字转化成编号 53 // cout<<v1<<" "<<v2<<endl; 54 if(findd(v1)!=findd(v2)) 55 faa[findd(v1)]=findd(v2);//并查集部分 56 } 57 cin>>k; 58 for(int i=1;i<=k;++i) 59 { 60 cin>>s>>s1; 61 if(findd(find(s1))==findd(find(s)))//转换成编号,并查集部分 62 cout<<"Yes."<<endl;//输出 63 else 64 cout<<"No."<<endl; 65 } 66 return 0; 67 }
--------------------------
May MIKU be with you.
--------------