巧妙的一题,利用已知的正方形建立节点和节点之间的连接关系,注意这里的节点其实就是正方形的各个边的信息,同时利用一个"^1"将字母相同符号相反的两个边映射到同一个编号d,建立编号d到d自己的连接,这样便于在后面的拓扑排序中找到所谓的“回路‘,从而判断出是存在无限循环的正方形的连接,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
using namespace std;
int n;
int connect[52][52];
int flag[52];
int getId(char a,char b){
return (a - 'A') * 2 + ((b=='+')?0:1);
}
void construct(char a1,char a2,char b1,char b2){
if (a1 == '0' || b1 == '0') return;
int index1 = getId(a1,a2)^1;
int index2 = getId(b1,b2);
connect[index1][index2] = 1;
}
bool toport(int index){
flag[index] = -1;
for (int i = 0; i < 52; i++){
if (connect[index][i]){
if (flag[i] < 0) return true;
if (!flag[i] && toport(i)) return true;
}
}
flag[index] = 1;
return false;
}
int main(){
while (cin >> n){
memset(connect,0,sizeof(connect));
for (int i = 0; i < n; i++){
string s;
cin >> s;
for (int a = 0; a < 4; a++){
for (int b = 0; b < 4; b++){
if (a != b){
construct(s[2*a],s[2*a+1],s[2*b],s[2*b+1]);
}
}
}
}
memset(flag,0,sizeof(flag));
int i;
for (i = 0; i < 52; i++){
if (flag[i] == 0){
if (toport(i)) break;
}
}
if (i == 52){
cout << "bounded" << endl;
}
else{
cout << "unbounded" << endl;
}
}
//system("pause");
return 0;
}