题目

展开
题目描述
In the NN country, there are nn cities, numbered from 11 to nn , and n - 1n−1 roads, connecting them. There is a roads path between any two cities.

There are mm bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by bus, you can travel from any stop on the route to any other. You can travel between cities only by bus.

You are interested in qq questions: is it possible to get from one city to another and what is the minimum number of buses you need to use for it?

输入格式
The first line contains a single integer nn ( 2 \le n \le 2 \cdot 10^52≤n≤2⋅10
5
) — the number of cities.

The second line contains n - 1n−1 integers p_2, p_3, \ldots, p_np
2

,p
3

,…,p
n

( 1 \le p_i < i1≤p
i

<i ), where p_ip
i

means that cities p_ip
i

and ii are connected by road.

The third line contains a single integer mm ( 1 \le m \le 2 \cdot 10^51≤m≤2⋅10
5
) — the number of bus routes.

Each of the next mm lines contains 22 integers aa and bb ( 1 \le a, b \le n1≤a,b≤n , a \neq ba


=b ), meaning that there is a bus route between cities aa and bb . It is possible that there is more than one route between two cities.

The next line contains a single integer qq ( 1 \le q \le 2 \cdot 10^51≤q≤2⋅10
5
) — the number of questions you are interested in.

Each of the next qq lines contains 22 integers vv and uu ( 1 \le v, u \le n1≤v,u≤n , v \neq uv


=u ), meaning that you are interested if it is possible to get from city vv to city uu and what is the minimum number of buses you need to use for it.

输出格式
Print the answer for each question on a separate line. If there is no way to get from one city to another, print -1−1 . Otherwise print the minimum number of buses you have to use.

输入输出样例
输入 #1复制
7
1 1 1 4 5 6
4
4 2
5 4
1 3
6 7
6
4 5
3 5
7 2
4 5
3 2
5 3
输出 #1复制
1
3
-1
1
2
3
输入 #2复制
7
1 1 2 3 4 1
4
4 7
3 5
7 6
7 6
6
4 6
3 1
3 2
2 7
6 3
5 3
输出 #2复制
1
-1
-1
1
-1
1
说明/提示
Routes for first sample are marked on the picture.

思路

发现可以贪心,贪心可以倍增优化。

贪心策略:把路径拆开成两条链,起始点和结尾点为祖先后代关系的链,显然是深度越浅越好

然后就可以暴力爬。发现一种特殊情况:有路径可以穿过lca

那么就判一下,是否有路径起始点在(倍增跳过后的停留点)子树中。

如何判?子树中的点的dfs序一定 in[rt]<=x<=out[rt]

两个变量就是二维数点问题咯。。

代码

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+77;
struct edge{int link,next;
}e[N<<1];
struct event{int x,y,id,opt;
}b[N*5];
int m,q,n,head[N],tot;
void add_edge(int u,int v){e[++tot]=(edge){v,head[u]}; head[u]=tot;
}
void insert(int u,int v){add_edge(u,v); add_edge(v,u);
}
int g[N][20],dep[N],fa[N][20],l[N],r[N],cnt;
void dfs(int u,int Fa){dep[u]=dep[Fa]+1; fa[u][0]=Fa; l[u]=++cnt;for (int i=1;i<20;i++) fa[u][i]=fa[fa[u][i-1]][i-1];for (int i=head[u];i;i=e[i].next){int v=e[i].link;if (v!=Fa) dfs(v,u);}r[u]=cnt;
}
int LCA(int u,int v){if (dep[u]<dep[v]) swap(u,v);int delta=dep[u]-dep[v];for (int i=0;i<20;i++) if (delta&(1<<i)) u=fa[u][i];for (int i=19;i>=0;i--) if (fa[u][i]!=fa[v][i]) u=fa[u][i],v=fa[v][i];if (u!=v) return fa[u][0];return u;
}
void init(){n=read();for (int i=2;i<=n;i++) insert(i,read());dfs(1,0); m=read(); tot=0;for (int i=1;i<=m;i++){int u=read(),v=read(),lca=LCA(u,v);if (l[u]>l[v]) swap(u,v);if (!g[u][0]||dep[lca]<dep[g[u][0]]) g[u][0]=lca;if (!g[v][0]||dep[lca]<dep[g[v][0]]) g[v][0]=lca;b[++tot]=(event){l[u],l[v],0,1};}
}
void Dfs(int u,int Fa){for (int i=head[u];i;i=e[i].next){int v=e[i].link;if (v!=Fa){Dfs(v,u);if (!g[u][0]||g[v][0]&&dep[g[v][0]]<dep[g[u][0]]) g[u][0]=g[v][0];}}
}
bool cmp(event A,event B){return A.x<B.x||(A.x==B.x&&A.id<B.id);
}
int bit[N];
int lowbit(int x){return x&(-x);
}
void update(int x){for (;x<=n;x+=lowbit(x)) bit[x]++;
}
int query(int x){int sum=0;for (;x;x-=lowbit(x)) sum+=bit[x];return sum;
}
int ans[N],ANS[N];
void solve(){Dfs(1,0);for (int i=1;i<=n;i++) if (g[i][0]==i) g[i][0]=0;for (int i=1;i<20;i++)for (int j=1;j<=n;j++) g[j][i]=g[g[j][i-1]][i-1];q=read();for (int i=1;i<=q;i++){int u=read(),v=read(),lca=LCA(u,v);if (l[u]>l[v]) swap(u,v);for (int j=19;j>=0;j--) if (g[u][j]&&dep[g[u][j]]>dep[lca]) u=g[u][j],ans[i]+=(1<<j);for (int j=19;j>=0;j--) if (g[v][j]&&dep[g[v][j]]>dep[lca]) v=g[v][j],ans[i]+=(1<<j);if ((!g[u][0]&&u!=lca)||(!g[v][0]&&v!=lca)) {ans[i]=-1; continue;}if (u==lca||v==lca) ans[i]++;else {ans[i]+=2;b[++tot]=(event){r[u],r[v],i,1};b[++tot]=(event){l[u]-1,r[v],i,-1};b[++tot]=(event){r[u],l[v]-1,i,-1};b[++tot]=(event){l[u]-1,l[v]-1,i,1};}}sort(b+1,b+1+tot,cmp);for (int i=1;i<=tot;i++){if (!b[i].id) update(b[i].y);else ANS[b[i].id]+=b[i].opt*query(b[i].y);}for (int i=1;i<=q;i++) writeln(ans[i]-(ANS[i]>0));
}
int main(){init(); solve();return 0;
}

CF983E NN country相关推荐

  1. HDU-5723 Abandoned country

    Problem Description An abandoned country has n(n≤100000) villages which are numbered from 1 to n. Si ...

  2. Abandoned country

    A Abandoned country 最小生成树 + 树上任意点对距离之和 树上任意点对距离之和: 计算时考虑每一个边,它的贡献值为它的 左端点以左的点的个数 * 右端点以右的点的个数 * 该边的权 ...

  3. torch.nn.functional.cross_entropy.ignore_index

    ignore_index表示计算交叉熵时,自动忽略的标签值,example: import torch import torch.nn.functional as F pred = [] pred.a ...

  4. 通俗理解tf.nn.conv2d() tf.nn.conv3d( )参数的含义 pytorhc 卷积

    20210609 例如(3,3,(3,7,7))表示的是输入图像的通道数是3,输出图像的通道数是3,(3,7,7)表示过滤器每次处理3帧图像,卷积核的大小是3 x 7 x 7. https://blo ...

  5. Pytorch的默认初始化分布 nn.Embedding.weight初始化分布

    一.nn.Embedding.weight初始化分布 nn.Embedding.weight随机初始化方式是标准正态分布  ,即均值$\mu=0$,方差$\sigma=1$的正态分布. 论据1--查看 ...

  6. nn.moduleList 和Sequential由来、用法和实例 —— 写网络模型

    对于cnn前馈神经网络如果前馈一次写一个forward函数会有些麻烦,在此就有两种简化方式,ModuleList和Sequential.其中Sequential是一个特殊的module,它包含几个子M ...

  7. pytorch nn.Embedding

    pytorch nn.Embedding class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_n ...

  8. PyTorch里面的torch.nn.Parameter()

    在刷官方Tutorial的时候发现了一个用法self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size)),看了官方教程里面的解释也是云里雾里, ...

  9. pytorch nn.LSTM()参数详解

    输入数据格式: input(seq_len, batch, input_size) h0(num_layers * num_directions, batch, hidden_size) c0(num ...

最新文章

  1. python codecs.open()及文件操作-文本处理 with open
  2. 有哪些适合远程办公的软件值得推荐?
  3. 广义线性模型?链接函数?sigmoid和softmax?Logistic处理多分类问题?logistic回归处理超大数据?使用logistic和randomsearch进行组合获取最优参数组合、优缺点
  4. centos桌面进入服务器,解决如何在centos7桌面中打开终端_网站服务器运行维护
  5. uboot 命令使用
  6. linux查看无线网卡频率,查看无线网卡工作模式
  7. C++运算符重载(10)
  8. BCB中与路径文件名相关的几个函数!
  9. 网络安全与信息安全【知识点】
  10. Jsp+Ssm+Mysql实现的房屋租赁租房管理系统
  11. Dorado7自定义下拉框
  12. webpack重复打包同名依赖包
  13. Representation Learning 表示学习(简单笔记)
  14. mds聚类matlab,机器学习C9笔记:MDS聚类可视化
  15. php 立方根,PHP立方根
  16. 石狮子吃了四十四个涩柿子
  17. sinc函数卷积_11-2   Sinc 函数与矩形脉冲
  18. 【力扣时间】【825】【中等】适龄的朋友
  19. JS 数组 isAarray() typeof push() unshift() splice()替换/删除/插入 slice()切片 join() split() reverse concat
  20. 每天一个小技巧——网易邮箱配置阿里云企业邮箱配置信息设置

热门文章

  1. 抖音最火刺激战场S5新赛季灵敏度:用过的都说好,建议收藏
  2. 微信内置浏览器导出Excel表格功能
  3. 【应用安全】S-SDLC安全开发生命周期
  4. c语言输入密码并将密码掩盖住
  5. 最值得入手的五款骨传导耳机,几款高畅销的骨传导耳机
  6. 商城项目解析(前端页面知识,用户如何访问服务器,hosts的修改,nginx)
  7. write as a reader
  8. scala2.11.8安装
  9. 2017年第26届上海国际连锁加盟展览会会刊(参展商名录)
  10. 汉字拼音的一个解决方法(初具使用价值)