【发布时间】:2020-04-23 04:40:26
【问题描述】:
我正在尝试使用 gecode 求解线性方程 15 * x + y + 0.4*z == 100。我想打印 x,y,z 的值。但是,当我运行以下代码时,
class LinearEq1 : public Space {
protected:
IntVar x;
IntVar y;
IntVar z;
public:
LinearEq1(void) :x(*this,-100,100), y(*this, -100, 100), z(*this, -100,100) {
// no leading zeros
rel(*this, x, IRT_GR, 0);
rel(*this, y, IRT_GR, 0);
rel(*this, z, IRT_GR, 0);
rel(*this, 15 * x + y + 0.4*z == 100);
}
// search support
LinearEq1(LinearEq1& s) : Space(s) {
x.update(*this, s.x);
y.update(*this, s.y);
z.update(*this, s.z);
}
virtual Space* copy(void) {
return new LinearEq1(*this);
}
// print solution
void print(void) const {
std::cout << x<<" "<<y<< " "<<z<<std::endl;
}
};
// main function
int main(int argc, char* argv[]) {
// create model and search engine
LinearEq1* m = new LinearEq1;
DFS<LinearEq1> e(m);
delete m;
// search and print all solutions
LinearEq1* s = e.next();
s->print();
return 0;
}
我得到的输出为 [1..6] [10..85] [1..100]。但我期待一个有效的解决方案,如 1 83 5 分别作为 x y z 值的答案。有人可以解释一下吗??
【问题讨论】:
-
2 66 10 不是一个有效的解决方案吗? (希望我没有犯错 - 我在脑海中解决了。);-) 事实上,你的方程 15 * x + y + 0.4*z == 100 有一组解和 x、y 和 z 的允许范围定义了这个集合的大小(即使 x、y、z 必须是整数值)。所以,如果解决方案是一组元素,我相信你不能期望得到一个特定的元素。为此,您必须提供更多约束。 (我必须承认我第一次在你的 Q 中听说过 Gecode,并阅读了文档的前几页。 - 出于好奇。)
-
... 但是,Modeling and Programming with Gecode 第 19 页上显示的示例看起来非常相似。所以,我希望(没有更深入的知识),如果你想要一种解决方案,那么你必须为 x 选择一个值,分别调整约束。 (例如,通过收紧 x 的范围)并再次求解,对 y 重复该操作,直到得到包含 1(或 0)个元素的解。
-
也许,这就是你要找的……在上面的链接文档中。第 27 页:2.5 最佳解决方案搜索。
标签: c++ solver constraint-programming gecode