实验项目三:搜索算法
《算法设计与分析》实验报告实验项目(三)搜索算法
return --total;
}
int main() {
int min;
cout << "第1 种方案:" << endl;
min = pull(3, 7);
cout << "第2 种方案:" << endl;
if (min > pull(7, 3))cout << "第2 种方案步骤最少。";
else cout << "第1 种方案步骤最少。";
return 0;
}
运行结果:
2、用非递归回溯算法
.......完成数独求解。
“数独”是一种智力游戏,一般认为起源于“正交拉丁方”,经日本人推广后风靡全球。下图是一个数独的示例,需要根据9 ×9 盘面上的已知数字,推理出所有剩余空格的数字,并且满足同一行、同一列、每一个同色九宫内的数字均含1~9 不重复:
int i,j;
for(i=0;i<9;i++){
gets(str[i]);
}
for(i=0;i<9;i++){
for(j=0;j<9;j++){
a[i][j] = str[i][j] - '0';
}
}
backtrack(0);
return 0;
}
运行结果:
3、用分支与限界策略
.......求解货物调运问题
某大型集团公司在全国有m (1 < m≤ 20) 个产品生产基地(通称产地),用A i表示(i = 1, 2, …, m),需要分别将这些物质调运到n (1 < n≤ 20) 个集中消费的地区(通称销地),用B j表示(j = 1, 2, …, n)。
已知这m个产地的产量分别为a1, a2, …, a m(简写为a i),n个销地的销量分别为b1, b2, …, b n(简写为b j),从第i个产地到第j个销地的单位货运价格为c i j,并且总产
量和总销量不一定相等。
应当如何制定调运方案,在尽可能地满足销量的前提下,使得总的运输费用为最小。
例:某集团公司的产量和销量以及单位运价表(千元/吨)
其总运费最小的调运方案为:
运费总计:5 ? 3 + 2 ? 10 + 3 ? 1 + 1 ? 8 + 6 ? 4 + 3 ? 5 = 85(千元)。
源代码:
#include
#include
#define min(x,y) (x using namespace std; int freight[3][4] = { {3,11,3,10},{1,9,2,8},{7,4,10,5} }; int sales[4] = { 3,6,5,6 }; int production[3] = { 7,4,9 }; int mincost = 999; int key[5][3] = { {1,3,2},{2,1,3},{2,3,1},{3,2,1},{3,1,2} }; struct NodeType { int r[4]; int lb; int pro[3][4] = { 0 }; bool operator <(const NodeType& s) const {return lb > s.lb;} }; void ret() { sales[0] = 3, sales[1] = 6, sales[2] = 5, sales[3] = 6; production[0] = 7, production[1] = 4, production[2] = 9; } void bound(NodeType& e) { int sum = 0, j; for (int m = 0; m < 4; m++) { j = e.r[m]; int temp, i = 0; qu.pop(); if (mincost > e.lb) { mincost = e.lb; } e1.r[0] = e.r[0]; for (int k = 1; k < 4; k++) { e1.r[k] = key[j][k - 1]; } j++; bound(e1); ret(); if (e1.lb <= mincost) qu.push(e1); } cout <<"总运费最小的调运方案为:"<< endl; cout << "\tB1\tB2\tB3\tB4" << endl; cout << endl; for (int i = 0; i < 3; i++) { cout <<"A"< for (int j = 0; j < 4; j++) { cout << e.pro[i][j] << "\t"; } cout << endl; cout << endl; } cout << endl; } int main() { int j = 0; int min = 100; bfs(); cout << "\t运输的最小费用为:"; cout << mincost << endl; return 0; } 运行结果: