您的位置:首页 > 其它

动态规划 0/1 背包问题, 最短路径问题

2015-08-31 15:52 411 查看
http://blog.csdn.net/wangran51/article/details/7674832
http://blog.csdn.net/xuefeng0707/article/details/7830469
0/1 背包:

const int N = 5;

101 static int mw(int w[], int v[], int c)

102 {

103 int max[6][12];

104 for (int j = 0; j <w[1]; j++)

105 max[1][j] = 0;

106 for (int j = w[1]; j <=c; j++)

107 max[1][j] = v[1];

108 int m, tmp;

109 for (int i = 2; i <=N; i++) {

110 for (int j = 0; j <=c; j++) {

111 m = max[i-1][j];

112 if (j >= w[i]) {

113 tmp = max[i-1][j-w[i]] + v[i];

114 if (tmp > m)

115 m = tmp;

116 }

117 max[i][j] = m;

118 }

119 }

120 list<int> q;

121 int j = c;

122 for (int i = N; i > 1; i--)

123 if (max[i][j] != max[i-1][j]) {

124 q.push_front(i);

125 j -= w[i];

126 }

127 if (j > w[1])

128 q.push_front(1);

129 list<int>::iterator it = q.begin();

130 for (; it != q.end(); ++it)

131 cout<<*it<<" ";

132 cout<<endl;

133 return max
[c];

134 }

135

136

137

138 void zeroOne() {

139 int w[] = {0, 2, 2, 6, 5, 4};

140 int v[] = {0, 6, 3, 5, 4, 6};

141 int c = 10;

142 int max = mw(w, v, c);

143 cout<<"max: "<<max<<endl;

144 }

最短路径:

145 const int x = 9999;

146 static void fpath(int a[][6])

147 {

148 int i, j, k;

149 int dist[6];

150 dist[0] = 0;

151 for (i =1; i < 6; i++) {

152 k = 1000;

153 for (j= 0; j < i; j++) {

154 if (a[j][i] != x)

155 if ((dist[j] + a[j][i]) < k)

156 k = dist[j] + a[j][i];

157 }

158 cout<<endl;

159 dist [i] = k;

160 }

161 i = 5;

162 int path[6];

163 k =1;

164 path[0] = 5;

165 while (i > 0) {

166 for (j = i -1; j >=0; j--) {

167 if (a[j][i] != x) {

168 int b = dist[i] - a[j][i];

169 if (b == dist[j]) {

170 path[k++] = j;

171 i = j;

172 break;

173 }

174 }

175 }

176 }

177 for (i = 0; i < 6; i++)

178 cout<<dist[i]<<" ";

179 cout<<endl;

180 for (i = 0; i < 6; i++)

181 cout<<path[i]<<" ";

182 cout<<endl;

183 }

184 void shortPath()

185 {

186 int a[6][6] = {

187 {x,2,4,x,x,x},

188 {x,x,2,3,x,x},

189 {x,x,x,3,x,x},

190 {x,x,x,x,4,1},

191 {x,x,x,x,x,7}

192 };

193 fpath(a);

194 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: