struct cell
{
int father;
int count;
};
const int maxlength= 20;
void Union(int a, int b, cell* c);
int find(int a, cell* c);
void initial(int a, cell* c);
void equiva(cell* c, int n);
void output(cell* c, int n);
int main()
{
cell c[maxlength];
int i, m;
cout<<"输入集合元素,以-1结束\n";
for(i=0; m>0; i++) //输入开始的各个元素
{
cin>>m;
if(m>0)
initial(m, c); //把每个元素建立一个自己的集合
}
i--;
equiva(c, i); //求出数组c中的等价类
cout<<"输出各等价类:\n";
output(c, i); //输出等价类
return 0;
}
void Union(int a, int b, cell* c) //合并数组c中的a, b两个集合
{
if(c[a].count>c[b].count)
{
c[b].father=a;
c[a].count+=c[b].count;
}
else
{
c[a].father=b;
c[b].count+=c[a].count;
}
}
int find(int a, cell* c) //在数组c中查找元素a所在的集合的根结点
{
int i=a;
while(c[i].father)
i=c[i].father;
return i;
}
void initial(int a, cell* c) //把数组c中的每个元素各建立一个只包含元素自己集合
{
c[a].father=0;
c[a].count=1;
}
void equiva(cell* c, int n) //n记录c数组中元素的个数,求出数组c中的等价类
{
int i, j, m, k;
for(i=1; i<=n; i++)
{
initial(i, c);
}
cout<<"输入等价的结点,以(0,0)结束\n";
cin>>i>>j; //输入等价的结点,以(0,0)结束
while((i||j))
{
k=find(i,c);
m=find(j,c);
if(k != m)
Union(k, m, c);
cin>>i>>j;
}
}
void output(cell* c, int n) //输出数组c中的等价类, n为元素的个数
{
int i, j=0, b[maxlength], m;
for(i=1; i<=n; i++)
{
if(c[i].father==0)
{
b[j++]=i;
}
}
m=j;
for(i=0; i<m; i++)
{
for(j=1; j<=n; j++)
{
if(b[i]==find(j, c))
cout<<j<<" ";
}
cout<<endl;
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
C++数据结构等价类实现
共10个文件
o:2个
cpp:2个
h:1个
4星 · 超过85%的资源 需积分: 49 103 下载量 23 浏览量
2010-04-12
20:35:32
上传
评论 6
收藏 161KB RAR 举报
温馨提示
C语言数据结构实验课上的一个作业,实现等价类,内容是用C++写的,但是C语言的数据结构
资源推荐
资源详情
资源评论
收起资源包目录
dengjialei.rar (10个子文件)
dengjialei
main.cpp 474B
dengjialei.cpp 1KB
pro.h 235B
dengjialei.depend 254B
dengjialei.layout 440B
obj
Debug
dengjialei.o 115KB
main.o 113KB
dengjialei.exe 570KB
dengjialei.cbp 1KB
新建 文本文档.txt 2KB
共 10 条
- 1
gupanyueleng
- 粉丝: 1
- 资源: 11
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页