2020年b组蓝桥杯真题 七段码
试题E 七段码
DFS+并查集,使用并查集判断是否连成一片
#include <cstdio>
using namespace std;
int res = 0;
bool visit[7];
int lian[7][7] = {
{ 0, 1, 0, 0, 0, 1, 0 },
{ 1, 0, 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0 },
{ 0, 0, 0, 1, 0, 1, 1 },
{ 1, 0, 0, 0, 1, 0, 1 },
{ 0, 1, 1, 0, 1, 1, 0 }
};
int fa[7];
int rank[7];
int find(int i) {
while(i != fa[i]) {
i = fa[i];
}
return i;
}
void merge(int a, int b) {
int x = find(a);
int y = find(b);
if (rank[x] < rank[y]) {
fa[x] = y;
} else if (rank[x] > rank[y]) {
fa[y] = x;
} else {
fa[x] = y;
rank[y]++;
}
}
bool check() {
for (int i = 0; i < 7; i++) {
fa[i] = i;
rank[i] = 0;
}
for (int i = 0; i < 7; i++) {
if (visit[i]) {
for (int j = i+1; j < 7; j++) {
if (visit[j] && lian[i][j]) {
merge(i, j);
}
}
}
}
int zu = 100;
for (int i = 0; i < 7; i++) {
if (visit[i]) {
if (zu == 100) {
zu = find(i);
} else {
if (find(i) != zu) {
return false;
}
}
}
}
return true;
}
void dfs(int i) {
if (i == 7) {
if (check()) {
res++;
}
return;
}
visit[i] = true;
dfs(i+1);
visit[i] = false;
dfs(i+1);
}
int main() {
dfs(0);
printf("%d", res - 1); // 减去全不亮的情况
return 0;
}