@lunar
2016-03-15T16:09:39.000000Z
字数 1859
阅读 1560
HiHo
简单的并查集,不过这里学了一下std::map的用法。啊啊啊啊这种stl的东西应该大一就开始学了。。为什么到现在还不会啊。。
map是一个C++的标准容器,提供的主要是一对一关系,比如,一个学生的姓名和他的学号。给出姓名要得到他的学号,如果开一个string数组来比较会很低效,map可以有效的解决这个问题。
在map里的一一对应我们叫做key-value 对于,也就是给出一个key,map可以返回value。
map<string,int>studentList; studentList["张三"]=123; studentList.insert(pair<string,int>("江蛤",124));map<string,int>::iterator lIt; lIt = studentList.find("张三"); lIt = studentList.end()那么说明没有该数据,否则通过lIt->second可以获得该value值。
map<string,int>stu;stu["蛤蛤"]=123;stu["嘻嘻"]=124;map<string,int>::iterator lIt1;lIt1 = stu.find("墨蛤");if(lIt1== stu.end()) cout << "找不到蛤蛤";// 这里应该会输出 找不到蛤蛤lIt1 = stu.find("嘻嘻");cout << lIt1->second; //这里应该会输出 124
map的使用中重要的是不要混淆了key和value。
#include<iostream>#include<map>using namespace std;int n;std::map<string,int>peopleList;int cla[100005];int count=0;int findCla(int a){int t=a;while(a!=cla[a]) a =cla[a];while(t!=cla[t]) {cla[t]=a;t=cla[t];}return a;}void unio(int a,int b){int aa = findCla(a);int bb = findCla(b);if(aa<bb)cla[bb]=aa;elsecla[aa]=bb;}int main(){cin >> n;for(int i=0;i<n;i++){int model;string jia;string yi;cin >> model;cin >>jia;cin >>yi;if(!model){map<string,int>::iterator lIt1;lIt1 = peopleList.find(jia);map<string,int>::iterator lIt2;lIt2 = peopleList.find(yi);int x,y;if(lIt1 == peopleList.end()) {peopleList[jia] = count;x = count++;cla[x] = x;}else x = lIt1 -> second;if(lIt2 == peopleList.end()) {peopleList[yi] = count;y = count++;cla[y] = y;}else y = lIt2 -> second;unio(x,y);}else{map<string,int>::iterator lIt1;lIt1 = peopleList.find(jia);map<string,int>::iterator lIt2;lIt2 = peopleList.find(yi);int x,y;if(lIt1 == peopleList.end()) {peopleList[jia] = count;x = count++;cla[x] = x;}else x = lIt1 -> second;if(lIt2 == peopleList.end()) {peopleList[yi] = count;y = count++;cla[y] = y;}else y = lIt2 -> second;if(findCla(x)==findCla(y)) cout << "yes"<<endl;else cout << "no" << endl;}}return 0;}