## 动态规划水库铺路问题
在A处有一水库,现需要从A点铺设一条管道到E点,边上的数字表示与其相连的两个地点之间所需修建的管道长度,用c数组表示,例如c(A,B1)=2。现要找出一条从A到E的修建线路,使得所需修建的管道长度最短。
#include
using namespace std;
#define MAX 30
typedef struct
{
int x[10];
}WAY;
WAY a[MAX][MAX];
int b[MAX] = { 0 }, c[MAX];
int sum = 0, min = 999999999;
int n=4;
void bfs(int s, int m)
{
if (s>n)
{
if (sum < min)
{
min = sum;
for (int i = 1; i <= n; i++)
c[i] = b[i];
}
return;
}
for (int i = 1; i <= 3; i++)
{
if (a[s][m].x[i] <= 0) continue;//跳过不连通的路
b[s] = 1;
sum += a[s][m].x[i];
bfs(s + 1, i);
sum-= a[s][m].x[i];
}
}
int main()
{
a[1][1].x[1] = 2, a[1][1].x[2] = 4, a[1][2].x[3] = 3;
a[2][1].x[1] = 7, a[2][1].x[2] = 4, a[2][1].x[3] = -1;
a[2][2].x[1] = 3, a[2][2].x[2] = 2, a[2][2].x[3] = 4;
a[2][3].x[1] = 6, a[2][3].x[2] = 2, a[2][3].x[3] = 5;
a[3][1].x[1] = 3, a[3][1].x[2] = 4, a[3][1].x[3] = -1;
a[3][2].x[1] = 6, a[3][2].x[2] = 3, a[4][1].x[3] = -1;
a[3][2].x[1] = 3, a[3][3].x[2] = 3, a[3][3].x[3] = -1;
a[4][1].x[1] = 3, a[4][1].x[2] = -1, a[4][1].x[3] = -1;
a[4][2].x[1] = 4, a[4][2].x[2] = -1, a[4][3].x[3] = -1;
bfs(1, 1);
for (int i = 1; i <= n; i++)
cout << c[i] << " ";
cout << endl;
cout << min << endl;
return 0;
}