题目链接如下:
Online Judge
这道题我完全没思路,看了刘汝佳书上的分析才写出来。“把标号看成点,正方形看作边,得到一个有向图。当且仅当图中存在有向环时有解。只需要做一次拓扑排序即可。”这个思路真的太厉害了……
下面这个应该是参考了刘汝佳的原代码 紫书刷题 UVA1572 自组合(Self-Assembly)-CSDN博客
非常简洁。里面有两个点:用dfs来找有向环,还有用亦或^,偶数亦或1为自身+1,奇数亦或1为自身-1;当0,1对应A+,A-,2,3对应B+,B-,.... 时,可以用亦或快速找到对应标号的下标。
我写的要复杂一些,如下:
#include
#include
#include
const int maxx = 52;
// #define debug
int n;
int in[maxx], vis[maxx];
int edge[maxx][maxx];
std::string str;
int a[4];
bool topological(){
int cnt = 0;
while (1){
bool flag = false;
for (int i = 0; i < maxx; ++i){
if (!vis[i] && !in[i]){
vis[i] = 1;
cnt++;
flag = true;
for (int j = 0; j < maxx; ++j){
if (edge[i][j]){
in[j]--;
}
}
}
}
if (!flag){
break;
}
}
return cnt == maxx ? true : false;
}
int main(){
#ifdef debug
freopen("0.txt", "r", stdin);
freopen("1.txt", "w", stdout);
#endif
while (scanf("%d", &n) == 1){
std::fill(in, in + maxx, 0);
std::fill(vis, vis + maxx, 0);
std::fill(edge[0], edge[0] + maxx * maxx, 0);
while (n--){
std::cin >> str;
for (int i = 0; i < 4; ++i){
if (str[2 * i] == '0'){
a[i] = -1;
} else {
a[i] = str[2 * i] - 'A';
if (str[2 * i + 1] == '-'){
a[i] += 26;
}
}
}
for (int i = 0; i < 4; ++i){
if (a[i] != -1){
for (int j = 1; j <= 3; ++j){
int temp = a[(i + j) % 4];
if (temp != -1){
temp = temp >= 26 ? temp - 26 : temp + 26;
edge[a[i]][temp] = 1;
}
}
}
}
}
for (int i = 0; i < maxx; ++i){
for (int j = 0; j < maxx; ++j){
in[i] += edge[j][i];
}
}
printf("%s\n", topological() ? "bounded" : "unbounded");
}
#ifdef debug
fclose(stdin);
fclose(stdout);
#endif
return 0;
}