1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| #include <bits/stdc++.h> using namespace std;
namespace FastIO { #define iL (1 << 20) char ibuf[iL],*iS = ibuf + iL,*iT = ibuf + iL; #define gc() (iS == iT ? (iT = (iS = ibuf) + fread(ibuf,1,iL,stdin),iS == iT ? EOF : *iS++) : *iS++) template<typename T> inline void read(T &a) { char ch;int sign = 0; for(ch = gc();!isdigit(ch);ch = gc()) if(ch == '-') sign = 1; a = ch & 15; for(ch = gc();isdigit(ch);ch = gc()) a = (a << 3) + (a << 1) + (ch & 15); if(sign) a = -a; } char Out[iL],*iter = Out; #define flush() fwrite(Out,1,iter - Out,stdout),iter = Out template<typename T> inline void write(T x,char end = '\n') { int c[40],l = 0;if(x < 0) *iter++ = '-',x = -x; do c[++l] = x % 10,x /= 10; while(x); while(l) *iter++ = c[l--] + '0'; *iter++ = end;flush(); } #undef iL #undef gc #undef flush } using namespace FastIO;
const int N = 3e5 + 5,Lg = 19; int n,m; vector<int> G[N]; int U[N],V[N],nd[N]; int L[N],R[N]; int tr[N]; #define lowbit(x) (x&(-x)) inline void upd(int x,int v) { for(int i = x;i <= n;i += lowbit(i)) tr[i] += v;} inline int Sum(int x) { int res = 0;for(int i = x;i;i ^= lowbit(i)) res += tr[i];return res;} inline int Qry(int x) { return Sum(R[x]) - Sum(L[x] - 1);} int anc[Lg][N],dep[N]; void dfs0(int x,int f) { anc[0][x] = f;L[x] = ++L[0]; dep[x] = dep[f] + 1; for(int i = 1;i < Lg;i++) anc[i][x] = anc[i - 1][anc[i - 1][x]]; for(auto y : G[x]) if(y != f) dfs0(y,x); R[x] = L[0]; } int lca(int x,int y) { if(dep[x] < dep[y]) swap(x,y); for(int i = Lg - 1;i >= 0;i--) if(dep[anc[i][x]] >= dep[y]) x = anc[i][x]; if(x == y) return x; for(int i = Lg - 1;i >= 0;i--) if(anc[i][x] != anc[i][y]) x = anc[i][x],y = anc[i][y]; return anc[0][x]; } int jump(int x,int y) { for(int i = Lg - 1;i >= 0;i--) if(dep[anc[i][x]] > dep[y]) x = anc[i][x]; return x; } int srt[N],tot; int crs[N],t2; int main() { read(n);read(m); for(int i = 2,x;i <= n;i++) read(x),G[x].push_back(i); dfs0(1,0); for(int i = 1;i <= m;i++) read(U[i]),read(V[i]); for(int i = 1;i <= m;i++) { int p = lca(U[i],V[i]); if(dep[U[i]] > dep[V[i]]) swap(U[i],V[i]); if(p == U[i]) { if(dep[V[i]] == dep[U[i]] + 1) return puts("-1"),0; nd[i] = jump(V[i],U[i]); srt[++tot] = i; } else crs[++t2] = i; } sort(srt + 1,srt + tot + 1,[&](const int &x,const int &y) { return dep[nd[x]] > dep[nd[y]];}); int ans = 0; for(int i = 1;i <= tot;i++) { int id = srt[i]; if(Qry(nd[id]) - Qry(V[id]) > 0) continue; else ++ans,upd(L[nd[id]],1); } int flg = 0; for(int i = 1;i <= t2;i++) if(Qry(U[crs[i]]) + Qry(V[crs[i]]) == ans) flg = 1; cout << ans + flg << endl; return 0; }
|