完整题目在图上,这是一道本科在读的lab的问题。太难了有点不会,刚学c++一年多。
2条回答 默认 最新
- threenewbee 2019-10-20 10:31关注
#include <iostream> #include <cstring> using namespace std; int* addtown(int * seed, int x, int* path, int pathn) { int canadd = 0; for (int i = 0; i < pathn; i++) { for (int j = 1; j <= seed[0]; j++) { if (path[i*2] == seed[j] && path[i*2+1] == x) { canadd = 1; break; } if (path[i*2+1] == seed[j] && path[i*2] == x) { canadd = 1; break; } } if (canadd) break; } if (!canadd) return NULL; int *p = new int[seed[0] + 2]; memcpy(p, seed, sizeof(int) * (seed[0] + 1)); p[0]++; p[p[0] - 1] = x; } int profit(int * seed) { if (seed[0] == 1) return 0; int max, min; max = min = seed[1]; for (int i = 2; i <= seed[0]; i++) { if (max < seed[i]) max = seed[i]; if (min > seed[i]) min = seed[i]; } return max - min; } int notin(int ** seed, int seedn, int x) { for (int i = 0; i < seedn; i++) { for (int j = 1; j <= seed[i][0]; j++) if (seed[i][j] == x) return 0; } return 1; } int solve(int ** seed, int selectedn, int n, int mn, int* routes) { if (selectedn == n) { int sum = 0; for (int i = 0; i < mn; i++) { sum += profit(seed[i]); } return sum; } int max = -1; for (int i = 0; i < n; i++) { if (notin(seed, mn, i)) { for (int j = 0; j < mn; j++) { int * seed1 = addtown(seed[j], i, routes, n - 1); if (seed1) { int maxsub = solve(seed, selectedn + 1, n, mn, routes); if (max < maxsub) max = maxsub; } } } } return max; } int main() { int townsn; cin >> townsn; int* towns = new int[townsn]; for (int i = 0; i < townsn; i++) cin >> towns[i]; int* routes = new int[(townsn - 1) * 2]; for (int i = 0; i < townsn - 1; i++) { int x, y; cin >> x >> y; routes[i*2] = x - 1; routes[i*2+1] = y - 1; } int k; cin >> k; int* mchs = new int[k]; int ** seed = new int*[k]; for (int i = 0; i < k; i++) { int x; cin >> x; mchs[i] = x - 1; seed[i] = new int[2]; seed[i][0] = 1; seed[i][1] = x - 1; } int result = solve(seed, k, townsn, k, routes); cout << result << endl; return 0; }
12
3 1 2 3 5 6 7 2 2 4 10 11
1 2
1 3
4 2
5 2
3 6
6 7
6 8
6 9
8 10
9 11
9 12
5
3 8 4 11 1212
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
- ¥15 vscode程序一直报同样的错,如何解决?
- ¥15 关于使用unity中遇到的问题
- ¥15 开放世界如何写线性关卡的用例(类似原神)
- ¥15 关于并联谐振电磁感应加热
- ¥15 this signal is connected to multiple drivers怎么解决
- ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
- ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
- ¥66 如何制作支付宝扫码跳转到发红包界面
- ¥15 pnpm 下载element-plus