给定A={1,2,3,4}上的关系R={<1,2>,<2,3>,<3,2>,<3,4>,<1,4>,<4,2>,<4,4>},S={<1,1>,<3,3>,<3,2>,<3,4>},求R和S的并集、交集、差集(相对补集)c语言
时间: 2023-08-21 11:01:41 浏览: 91
下面是使用C语言实现求解R和S的并集、交集、差集的代码:
```c
#include <stdio.h>
int main() {
int A[4] = {1, 2, 3, 4};
int R[7][2] = {{1, 2}, {2, 3}, {3, 2}, {3, 4}, {1, 4}, {4, 2}, {4, 4}};
int S[4][2] = {{1, 1}, {3, 3}, {3, 2}, {3, 4}};
int i, j, k;
int R_len = sizeof(R) / sizeof(R[0]);
int S_len = sizeof(S) / sizeof(S[0]);
int RS_union[11][2], RS_intersection[4][2], RS_difference[7][2];
int RS_union_len = 0, RS_intersection_len = 0, RS_difference_len = 0;
// 求并集
for (i = 0; i < R_len; i++) {
RS_union[RS_union_len][0] = R[i][0];
RS_union[RS_union_len][1] = R[i][1];
RS_union_len++;
}
for (i = 0; i < S_len; i++) {
int is_duplicate = 0;
for (j = 0; j < R_len; j++) {
if (S[i][0] == R[j][0] && S[i][1] == R[j][1]) {
is_duplicate = 1;
break;
}
}
if (!is_duplicate) {
RS_union[RS_union_len][0] = S[i][0];
RS_union[RS_union_len][1] = S[i][1];
RS_union_len++;
}
}
// 求交集
for (i = 0; i < R_len; i++) {
for (j = 0; j < S_len; j++) {
if (R[i][0] == S[j][0] && R[i][1] == S[j][1]) {
RS_intersection[RS_intersection_len][0] = R[i][0];
RS_intersection[RS_intersection_len][1] = R[i][1];
RS_intersection_len++;
}
}
}
// 求差集
for (i = 0; i < R_len; i++) {
int is_duplicate = 0;
for (j = 0; j < S_len; j++) {
if (R[i][0] == S[j][0] && R[i][1] == S[j][1]) {
is_duplicate = 1;
break;
}
}
if (!is_duplicate) {
RS_difference[RS_difference_len][0] = R[i][0];
RS_difference[RS_difference_len][1] = R[i][1];
RS_difference_len++;
}
}
// 输出并集
printf("R和S的并集为:{");
for (i = 0; i < RS_union_len; i++) {
printf("<%d,%d>", RS_union[i][0], RS_union[i][1]);
if (i != RS_union_len - 1) {
printf(",");
} else {
printf("}\n");
}
}
// 输出交集
printf("R和S的交集为:{");
for (i = 0; i < RS_intersection_len; i++) {
printf("<%d,%d>", RS_intersection[i][0], RS_intersection[i][1]);
if (i != RS_intersection_len - 1) {
printf(",");
} else {
printf("}\n");
}
}
// 输出差集
printf("R和S的差集为:{");
for (i = 0; i < RS_difference_len; i++) {
printf("<%d,%d>", RS_difference[i][0], RS_difference[i][1]);
if (i != RS_difference_len - 1) {
printf(",");
} else {
printf("}\n");
}
}
return 0;
}
```
运行结果如下:
```c
R和S的并集为:{<1,2>,<2,3>,<3,2>,<3,4>,<1,4>,<4,2>,<4,4>,<1,1>,<3,3>}
R和S的交集为:{<3,2>,<3,4>}
R和S的差集为:{<1,2>,<2,3>,<1,4>,<4,2>,<4,4>}
```
阅读全文