求到賓館的最長路。
開始想法是添加超級起點和終點,起點向所有山連接一條權爲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;
}