喜闻乐见卡输入,喜闻乐见调代码,喜闻乐见。
题目很简单,简单并查集。
难点以下几点
one
map的使用,把字符映射为数字。
two
并查集啦
three
喜闻乐见卡输入,调试好久卡好久。
four
调试半天找不到错误,于是换c,就过了。
再交代一条----并查集要初始化。么么哒
正确代码如下
#include<cstdio>
#include<map>
#include<string>
using namespace std;
int root[100002];
int co=1;
map<string,int>mm;
int find(int x)
{
return x==root[x]?x:find(root[x]);
}
void merge(int x,int y,int flag)
{
int xx,yy;
xx=find(x);
yy=find(y);
if(flag==0&&xx!=yy) root[xx]=yy;
else if(flag==1)
{
if(xx==yy) printf("yes\n");
else printf("no\n");
}
}
int main()
{
int n,q,i;
char str1[20],str2[20];
scanf("%d",&n);
for(i=1;i<=n;i++)
root[i]=i;
for(i=1;i<=n;i++)
{
scanf("%d",&q);
scanf("%s%s",str1,str2);
if(!mm.count(str1))
mm[str1]=co++;
if(!mm.count(str2))
mm[str2]=co++;
merge(mm[str1],mm[str2],q);
}
return 0;
}
喜闻乐见卡输入代码如下
#include<iostream>
#include<set>
#include<map>
using namespace std;
int father[10100];
void init(int n)
{
for(int i=1;i<=n;i++)
father[i]=i;
}
int find(int x)
{
return x==father[x]?x:find(father[x]);
}
int mearge(int a,int b)
{
a=find(a);
b=find(b);
if(a==b) return 1;
father[a]=b;
return 0;
}
set<string>s;
map<string,int>m;
int number=1;
int feipei(string &s1)
{
if(s.count(s1)) return m[s1];
else {s.insert(s1);m[s1]=number;number++;}
return m[s1];
}
int main()
{
int n;
cin>>n;
string s1,s2;
int num;
init(n);
while(n--)
{
cin>>num>>s1>>s2;
if(num==0) mearge(feipei(s1),feipei(s2));
if(num==1) {
int aa=find(m[s1]);
int bb=find(m[s2]);
if(aa==bb) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
}
return 0;
}