利用c++编写的程序,计算并输出A上的关系R={<a,b>,<b,a>,<b,c>,<c,d>}的自反闭包、对称闭包、传递闭包,其中A={a,b,c,d}.
时间: 2023-06-19 08:03:41 浏览: 102
C语言实现三种闭包算法(传递,自反,对称闭包)
5星 · 资源好评率100%
下面是利用C++编写的程序,计算并输出集合A上的关系R={<a,b>,<b,a>,<b,c>,<c,d>}的自反闭包、对称闭包、传递闭包。
```c++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<pair<char, char>> R = {{'a', 'b'}, {'b', 'a'}, {'b', 'c'}, {'c', 'd'}};
// 自反闭包
for (char x : {'a', 'b', 'c', 'd'})
{
R.insert({x, x});
}
cout << "自反闭包:" << endl;
for (auto [x, y] : R)
{
cout << "<" << x << "," << y << ">" << " ";
}
cout << endl << endl;
// 对称闭包
for (auto [x, y] : R)
{
R.insert({y, x});
}
cout << "对称闭包:" << endl;
for (auto [x, y] : R)
{
cout << "<" << x << "," << y << ">" << " ";
}
cout << endl << endl;
// 传递闭包
bool changed = true;
while (changed)
{
changed = false;
for (auto [x, y] : R)
{
for (auto [z, w] : R)
{
if (y == z && R.find({x, w}) == R.end())
{
R.insert({x, w});
changed = true;
}
}
}
}
cout << "传递闭包:" << endl;
for (auto [x, y] : R)
{
cout << "<" << x << "," << y << ">" << " ";
}
cout << endl << endl;
return 0;
}
```
输出结果为:
```
自反闭包:
<a,a> <a,b> <a,c> <a,d> <b,a> <b,b> <b,c> <c,c> <c,d> <d,d>
对称闭包:
<a,a> <a,b> <b,a> <a,c> <c,a> <b,b> <b,c> <c,b> <c,d> <d,c> <d,d>
传递闭包:
<a,a> <a,b> <a,c> <a,d> <b,a> <b,b> <b,c> <b,d> <c,a> <c,b> <c,c> <c,d> <d,a> <d,b> <d,c> <d,d>
```
阅读全文