AC:string
思路:只把限制条件存放在 vector 的元素 pair 中。每次排列后,遍历限制条件,得到 pair 的 first 和 second,就可以通过访问排列后自然数中的数字 first 的下一个位置是不是数字 second 来判断是否合法了。
因为出现的数最大为 9,所以可以把数存放到 string。不过要注意的是需要把数字转换为字符。查找的时候形参也得记得转为字符,否则始终是查找失败。
也可以把数存放到 vector 进行全排列,在下一个代码块中。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> P;
int main() {
int n, k;
cin >> n >> k;
string s;
for (int i = 0; i < n; ++i) s += i + '0';
vector<P> limits;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
int op;
cin >> op;
if (i != j && op == 0) limits.push_back(P(i, j)); //条件限制:i 后跟 j 是不允许的
}
//i 从 1 开始,最后为 k,求得是第 k 次排列
for (int i = 1; i < k;) {
bool isvalid = true;
for (int j = 0; j < limits.size(); ++j) {
int pos = s.find(limits[j].first + '0'); //error: 未 + '0',导致字符与数字比较
if (pos == string::npos) { //通过判断可以很容易发现上面错误
cout << "error";
exit(EXIT_FAILURE);
}
if (pos + 1 < s.size() && s[pos + 1] == (limits[j].second + '0')) { //防止 pos + 1 越界
isvalid = false;
break;
}
}
next_permutation(s.begin(), s.end()); //不管符不符合条件都得求出下次排列
if (isvalid) ++i;
}
for (int i = 0; i < s.size(); ++i) cout << s[i] << ' ';
return 0;
}
AC:vector
string 有成员函数 find,查找失败时会返回 string::npos。
而 vector 没有该成员函数,不过可以使用 <algorithm> 里的 find,查找失败时会返回 end()。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> P;
int main() {
int n, k;
cin >> n >> k;
vector<int> vec;
for (int i = 0; i < n; ++i) vec.push_back(i);
vector<P> limits;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
int op;
cin >> op;
if (i != j && op == 0) limits.push_back(P(i, j));
}
for (int i = 1; i < k;) {
bool isvalid = true;
for (int j = 0; j < limits.size(); ++j) {
vector<int>::iterator pos = find(vec.begin(), vec.end(), limits[j].first);
++pos;
if (pos != vec.end() && *pos == limits[j].second) { //note
isvalid = false;
break;
}
}
next_permutation(vec.begin(), vec.end());
if (isvalid) ++i;
}
for (int i = 0; i < vec.size(); ++i) cout << vec[i] << ' ';
return 0;
}