题意:求一条最长路径,路径中的节点入度和出度皆为1(忽略起始点和终点,起始点的出度必须为1),题目已经给出限定,每一个节点的入度皆小于等于1
Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.(终点只能是旅店)
For any integer i(1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.(得到的路径中每个节点的入度和出度皆为1)
The path contains as many objects as possible (k is maximal).(尽可能让这个路径上的节点数最多)
从终点到起始点进行构造,理论上效率更高(代码中时从起始点向终点构造)
思路明晰:如果有固定节点的,一定要从固定节点下手
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e5 + 5;
int n;
int A[MAXN], B[MAXN], O[MAXN], par[MAXN];
bool vis[MAXN];
void init() {
memset(O, 0, sizeof(O));
memset(vis, false, sizeof(vis));
for(int i = 0; i < MAXN; i ++) par[i] = i;
}
int main() {
while(~scanf("%d", &n)) {
init();
for(int i = 1; i <= n; i ++) {
scanf("%d", &A[i]);
}
for(int i = 1; i <= n; i ++) {
scanf("%d", &B[i]);
O[B[i]] ++;//记录出度
}
for(int i = 1; i <= n; i ++) {
if(O[B[i]] <= 1) {
par[B[i]] = i;//记录可以构成路径的节点
}
}
int dz = 0, c = 1;
for(int i = 1; i <= n; i ++) {
if(vis[i]) continue;
if(O[i] <= 1) {
int t = i,z = 1;
while(par[t] != t && !vis[i]) {//每个节点有且只会访问一次,因为入度为1
if(O[t] > 1) break;
z ++,t = par[t];
vis[t] = true;
}
//用于判断最终是否为旅店
if(A[t] == 1 && z > dz) dz = max(dz, z), c = i;
}
vis[i] = true;
}
printf("%d\n", dz);
while(par[c] != c) {
printf("%d ",c);
c = par[c];
}
printf("%d\n", c);
}
return 0;
}