hiho coder 并查集应用

喜闻乐见卡输入,喜闻乐见调代码,喜闻乐见。

题目很简单,简单并查集。

难点以下几点

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值