求到宾馆的最长路。
开始想法是添加超级起点和终点,起点向所有山连接一条权为0的边,所有宾馆向终点连接一条权为1的边。
然后只有出度为1的点才可以对后面进行更新(超级起点不算),做一遍spfa最长路,然后输出路径。
不知道为什么会TLE = =
然后重新想可能枚举所有起点,然后求当前起点的最长路。发现好麻烦。因为一个点有多条出的路径。dfs时间复杂度也太高。
没有想到反过来做。。枚举所有终点,因为所有点的入度一定为1或者0。枚举终点就简单得多了。
不断向上走直到走到一个点的出度为2即可。
AC代码:
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int MAX_NUMBER = 100006;
int pre[MAX_NUMBER];
int degree[MAX_NUMBER];
int is_hotel[MAX_NUMBER];
vector<int> ans;
vector<int> path;
int n;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", is_hotel + i);
}
for (int i = 1; i <= n; i++) {
scanf("%d", &pre[i]);
degree[pre[i]]++;
}
for (int i = 1; i <= n; i++) {
if (is_hotel[i]) {
path.clear();
path.push_back(i);
int cnt_node = i;
while (pre[cnt_node] && degree[pre[cnt_node]] == 1) {
path.push_back(pre[cnt_node]);
cnt_node = pre[cnt_node];
}
if (path.size() > ans.size()) {
ans = path;
}
}
}
printf("%d\n", ans.size());
for (int i = ans.size() - 1; i >= 1; i--) {
printf("%d ", ans[i]);
}
printf("%d\n", ans[0]);
return 0;
}