[关闭]
@lunar 2016-03-15T16:09:39.000000Z 字数 1859 阅读 1254

HiHo一下 Week14 并查集 + STL::map初探

HiHo


描述

输入

输出

样例

思路

简单的并查集,不过这里学了一下std::map的用法。啊啊啊啊这种stl的东西应该大一就开始学了。。为什么到现在还不会啊。。
map是一个C++的标准容器,提供的主要是一对一关系,比如,一个学生的姓名和他的学号。给出姓名要得到他的学号,如果开一个string数组来比较会很低效,map可以有效的解决这个问题。
在map里的一一对应我们叫做key-value 对于,也就是给出一个key,map可以返回value。

  1. map<string,int>stu;
  2. stu["蛤蛤"]=123;
  3. stu["嘻嘻"]=124;
  4. map<string,int>::iterator lIt1;
  5. lIt1 = stu.find("墨蛤");
  6. if(lIt1== stu.end()) cout << "找不到蛤蛤";// 这里应该会输出 找不到蛤蛤
  7. lIt1 = stu.find("嘻嘻");
  8. cout << lIt1->second; //这里应该会输出 124

map的使用中重要的是不要混淆了key和value。

代码

  1. #include<iostream>
  2. #include<map>
  3. using namespace std;
  4. int n;
  5. std::map<string,int>peopleList;
  6. int cla[100005];
  7. int count=0;
  8. int findCla(int a){
  9. int t=a;
  10. while(a!=cla[a]) a =cla[a];
  11. while(t!=cla[t]) {
  12. cla[t]=a;
  13. t=cla[t];
  14. }
  15. return a;
  16. }
  17. void unio(int a,int b){
  18. int aa = findCla(a);
  19. int bb = findCla(b);
  20. if(aa<bb)
  21. cla[bb]=aa;
  22. else
  23. cla[aa]=bb;
  24. }
  25. int main(){
  26. cin >> n;
  27. for(int i=0;i<n;i++){
  28. int model;
  29. string jia;
  30. string yi;
  31. cin >> model;
  32. cin >>jia;
  33. cin >>yi;
  34. if(!model){
  35. map<string,int>::iterator lIt1;
  36. lIt1 = peopleList.find(jia);
  37. map<string,int>::iterator lIt2;
  38. lIt2 = peopleList.find(yi);
  39. int x,y;
  40. if(lIt1 == peopleList.end()) {
  41. peopleList[jia] = count;
  42. x = count++;
  43. cla[x] = x;
  44. }else x = lIt1 -> second;
  45. if(lIt2 == peopleList.end()) {
  46. peopleList[yi] = count;
  47. y = count++;
  48. cla[y] = y;
  49. }else y = lIt2 -> second;
  50. unio(x,y);
  51. }else{
  52. map<string,int>::iterator lIt1;
  53. lIt1 = peopleList.find(jia);
  54. map<string,int>::iterator lIt2;
  55. lIt2 = peopleList.find(yi);
  56. int x,y;
  57. if(lIt1 == peopleList.end()) {
  58. peopleList[jia] = count;
  59. x = count++;
  60. cla[x] = x;
  61. }else x = lIt1 -> second;
  62. if(lIt2 == peopleList.end()) {
  63. peopleList[yi] = count;
  64. y = count++;
  65. cla[y] = y;
  66. }else y = lIt2 -> second;
  67. if(findCla(x)==findCla(y)) cout << "yes"<<endl;
  68. else cout << "no" << endl;
  69. }
  70. }
  71. return 0;
  72. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注