感覺是不是很久沒做水題了,最近開始各種坑,不論是訓練還是CF。。。
加之要去長春賽區,感覺中大出題有點偏向CF風格?所以最近打算把CF上tags 帶graphs的都做做吧。
這個題挺水的,直接根據題意,枚舉起點然後bfs找最長路就行了。諷刺的是,當時做這場DIV2的時候題都沒看懂。。。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<fstream>
#include<sstream>
#include<vector>
#include<string>
#include<cstdio>
#include<bitset>
#include<queue>
#include<stack>
#include<cmath>
#include<map>
#include<set>
#define FF(i, a, b) for(int i=a; i<b; i++)
#define FD(i, a, b) for(int i=a; i>=b; i--)
#define REP(i, n) for(int i=0; i<n; i++)
#define CLR(a, b) memset(a, b, sizeof(a))
#define debug puts("**debug**")
#define LL long long
#define PB push_back
#define MP make_pair
#define eps 1e-8
using namespace std;
const int maxn = 1e5 + 10;
int n, c[maxn], fa[maxn], d[maxn], out[maxn];
vector<int> G[maxn];
int ans, max_len, t, ss, tt;
void bfs(int x)
{
queue<int> q; q.push(x);
CLR(d, -1); d[x] = max_len = 0;
fa[x] = -1; t = x;
while(!q.empty())
{
int u = q.front(); q.pop();
REP(i, G[u].size())
{
int v = G[u][i];
//按題意要求走
if(d[v] != -1 || c[v] == 1) continue;
if(out[v] != 1) continue;
//記錄
d[v] = d[u] + 1;
fa[v] = u;
q.push(v);
if(d[v] > max_len) max_len = d[v], t = v;
}
}
}
int main()
{
scanf("%d", &n);
FF(i, 1, n+1) scanf("%d", &c[i]);
FF(i, 1, n+1)
{
scanf("%d", &t);
if(t) G[i].PB(t), G[t].PB(i), out[t]++;
}
ans = -1;
FF(i, 1, n+1) if(c[i])
{
bfs(i);
if(d[t] > ans) ans = d[t], ss = i, tt = t;
}
bfs(ss);
printf("%d\n", ans+1);
while(tt != -1)
{
printf("%d ", tt);
tt = fa[tt];
}
return 0;
}