Codeforces 350B Resort
题意: 这个题目关键还是读题。给定的是一个有向图,图中有N个点,每个点的前驱节点只有一个,但是后继节点可以有多个。在这个给定的有向图中,找一个最长的链,这条链满足:
该链上所有的点的出度小于等于1;而且终点必须是在若干给定的点集中。
思路:首先将与出度大于1的点有关的所有有向边统统删掉。然后从终点出发找前驱,求最长链并保存该链的终点。然后保存到结果集中,逆序输出就完了。
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
#define fst first
#define snd second
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef __int64 LL;
//typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int MAXN = 1e5 + 5;
const int MAXM = 100 + 5;
int N, M;
int type[MAXN], prior[MAXN];
int cnt[MAXN];
int vis[MAXN];
stack<int> S;
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while (~scanf("%d", &N)) {
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= N; i++) {
cnt[i] = 1;
}
for (int i = 1; i <= N; i++) {
scanf("%d", &type[i]);
}
for (int i = 1; i <= N; i++) {
scanf("%d", &prior[i]);
vis[prior[i]] ++;
}
for (int i = 1; i <= N; i++) {
if (vis[i] > 1) prior[i] = 0;
if (vis[prior[i]] > 1) prior[i] = 0;
}
int R = -1, cur;
for (int i = 1; i <= N; i++) {
if (!type[i]) continue;
cur = i;
int x = cnt[i];
while (prior[cur]) {
if (cnt[prior[cur]] > 1) {
x += cnt[prior[cur]];
break;
} else {
cur = prior[cur];
x ++;
}
}
cnt[i] = x;
cur = i;
if (~R) {
if (cnt[i] > cnt[R]) R = i;
} else {
R = i;
}
while (prior[cur]) {
if (cnt[prior[cur]]) break;
cnt[prior[cur]] = --x;
cur = prior[cur];
}
}
printf("%d\n", cnt[R]);
cur = R;
while (cur) {
S.push(cur);
cur = prior[cur];
}
bool fir = true;
while (!S.empty()) {
if (!fir) printf(" ");
fir = false;
int res = S.top();
S.pop();
printf("%d", res);
}
puts("");
}
return 0;
}