给定一个字符串的集合,格式如:{aaa bbb ccc}, {bbb ddd},{eee fff},{ggg},{ddd hhh}要求将其中交集不为空的集合合并,要求合并完成后的集合之间无交集,例如上例应输出{aaa bbb ccc ddd hhh},{eee fff}, {ggg}。
提示:并查集。
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int MLEN = 0;
//初始化各字符串集的hash
int initHash(int hash, char *p) {
char ch = *p;
int orHash = hash;
orHash |= 1 << (ch - 'a');
return orHash;
}
//从hash还原字符串
void getStrFromHash(int hash) {
if (!hash) {
return;
}
char str[MLEN];
int i = 0;
int dif = 0;
do {
if (hash & 1) {
str[i] = 'a' + dif;
i++;
}
dif++;
} while (hash = (hash >> 1));
str[i] = '\0';
i = 0;
printf("{%c%c%c", str[i++], str[i], str[i]);
while (str[i] != '\0') {
printf(",%c%c%c", str[i++], str[i], str[i]);
}
printf("}\n");
}
//获取并集最大长度
int getMaxLength(int len[]) {
int i = 0;
int sum = 0;
for (; i < SIZE; i++) {
sum += len[i];
}
return sum;
}
//合并
void unionSet(int hash[], int begin) {
if (!hash[begin] || begin + 1 == SIZE) {
return;
} else {
int i = begin + 1;
for (; i < SIZE; i++) {
if (hash[begin] & hash[i]) {
hash[begin] |= hash[i];
hash[i] = 0;
}
}
}
}
int main(void) {
char *p1[] = { "aaa", "bbb", "ccc" };
char *p2[] = { "bbb", "ddd" };
char *p3[] = { "eee", "fff" };
char *p4[] = { "ggg" };
char *p5[] = { "ddd", "hhh" };
char** p[] = { p1, p2, p3, p4, p5 };
int hash[SIZE] = { 0 };
int len[SIZE] = { 0 };
len[0] = sizeof(p1) / sizeof(char*);
len[1] = sizeof(p2) / sizeof(char*);
len[2] = sizeof(p3) / sizeof(char*);
len[3] = sizeof(p4) / sizeof(char*);
len[4] = sizeof(p5) / sizeof(char*);
MLEN = getMaxLength(len);
int i = 0, j = 0;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < len[i]; j++) {
hash[i] = initHash(hash[i], p[i][j]);
// puts(p[i][j]);
}
}
i = 0;
for (; i < SIZE; i++) {
unionSet(hash, i);
}
i = 0;
for (; i < SIZE; i++) {
getStrFromHash(hash[i]);
}
return EXIT_SUCCESS;
}