我正在尝试实现这个任务。我们在圆上有2n个点。因此,我们可以在它们之间创建n条弦。打印出所有不相交的n条弦的绘制方式。
例如:如果 n = 6。我们可以绘制 (1->2 3->4 5->6), (1->4, 2->3, 5->6), (1->6, 2->3, 4->5), (1->6, 2->5, 3->4)。
我已经通过从1->2, 4, 6创建一条弦并为2个剩余的间隔生成答案来开发了一个递归算法。但我知道有更有效的非递归方法。可能是通过实现NextSeq函数。
有人有任何想法吗?
更新:我确实缓存中间结果,但我真正想要找到GenerateNextSeq()函数,它可以通过前一个序列生成下一个序列,从而生成所有这样的组合。
顺便说一下,这是我的代码。
例如:如果 n = 6。我们可以绘制 (1->2 3->4 5->6), (1->4, 2->3, 5->6), (1->6, 2->3, 4->5), (1->6, 2->5, 3->4)。
我已经通过从1->2, 4, 6创建一条弦并为2个剩余的间隔生成答案来开发了一个递归算法。但我知道有更有效的非递归方法。可能是通过实现NextSeq函数。
有人有任何想法吗?
更新:我确实缓存中间结果,但我真正想要找到GenerateNextSeq()函数,它可以通过前一个序列生成下一个序列,从而生成所有这样的组合。
顺便说一下,这是我的代码。
struct SimpleHash {
size_t operator()(const std::pair<int, int>& p) const {
return p.first ^ p.second;
}
};
struct Chord {
int p1, p2;
Chord(int x, int y) : p1(x), p2(y) {};
};
void MergeResults(const vector<vector<Chord>>& res1, const vector<vector<Chord>>& res2, vector<vector<Chord>>& res) {
res.clear();
if (res2.empty()) {
res = res1;
return;
}
for (int i = 0; i < res1.size(); i++) {
for (int k = 0; k < res2.size(); k++) {
vector<Chord> cur;
for (int j = 0; j < res1[i].size(); j++) {
cur.push_back(res1[i][j]);
}
for (int j = 0; j < res2[k].size(); j++) {
cur.push_back(res2[k][j]);
}
res.emplace_back(cur);
}
}
}
int rec = 0;
int cached = 0;
void allChordsH(vector<vector<Chord>>& res, int st, int end, unordered_map<pair<int, int>, vector<vector<Chord>>, SimpleHash>& cach) {
if (st >= end)
return;
rec++;
if (cach.count( {st, end} )) {
cached++;
res = cach[{st, end}];
return;
}
vector<vector<Chord>> res1, res2, res3, curRes;
for (int i = st+1; i <=end; i += 2) {
res1 = {{Chord(st, i)}};
allChordsH(res2, st+1, i-1, cach);
allChordsH(res3, i+1, end, cach);
MergeResults(res1, res2, curRes);
MergeResults(curRes, res3, res1);
for (auto i = 0; i < res1.size(); i++) {
res.push_back(res1[i]);
}
cach[{st, end}] = res1;
res1.clear(); res2.clear(); res3.clear(); curRes.clear();
}
}
void allChords(vector<vector<Chord>>& res, int n) {
res.clear();
unordered_map<pair<int, int>, vector<vector<Chord>>, SimpleHash> cach; // intrval => result
allChordsH(res, 1, n, cach);
return;
}