HDU 4912 Paths on the tree
来源:互联网 发布:移动4g网络制式 编辑:程序博客网 时间:2024/05/17 01:28
题目:
给定一棵树和一些路径 问 最多能选出多少路径放在树上 使得各个路径间没有点交叉
思路:
LCA+贪心
对于一条路径 我们可以将它分成两部分 即 从u到lca 和 从v到lca 易知lca位于树上深度最浅的地方 而且如果这个lca被一条路径覆盖了 那么下面的子树都相当于被覆盖了
考虑到以x点为上述的lca点 那么如何选择经过x的路径呢 可以想到如果一条路径能放上去且不和子树中的路径冲突那么才去放它 为什么呢? 显然放一条路径相当于覆盖一棵树然后答案加一 那么如果这条路径和子树路径冲突放它是不值的 因为覆盖的树变大了 答案至少要减一再加一
因此得到策略 对于所有路径求lca 根据lca深度从深到浅安放路径 如果路径不和其他路径冲突则放上
代码:
#include<cstdio>#include<cstring>#include<algorithm>#include<vector>using namespace std;#define N 100010#define M 20#define mp(x,y) make_pair(x,y)int lca[N][M], dep[N], fa[N];vector<pair<int, int> > ask[N];vector<int> tree[N];int n, m, ans;void dfs(int u, int from) {int i, v;dep[u] = dep[from] + 1;lca[u][0] = from;for (i = 1; i < M; i++)lca[u][i] = lca[lca[u][i - 1]][i - 1];for (i = 0; i < tree[u].size(); i++) {v = tree[u][i];if (v != from)dfs(v, u);}}int getlca(int u, int v) {if (dep[v] > dep[u])swap(u, v);int i, tmp = dep[u] - dep[v];for (i = 19; tmp; i--) {if (tmp >= (1 << i)) {tmp -= (1 << i);u = lca[u][i];}}if (u == v)return u;for (i = 19; i >= 0; i--) {if (lca[u][i] != lca[v][i]) {u = lca[u][i];v = lca[v][i];}}return lca[u][0];}int getf(int x) {if (x != fa[x])fa[x] = getf(fa[x]);return fa[x];}void solve(int u, int from) {int i, v, f;for (i = 0; i < tree[u].size(); i++) {v = tree[u][i];if (v != from)solve(v, u);}for (i = 0; i < ask[u].size(); i++) {f = getf(ask[u][i].first);v = getf(ask[u][i].second);if (f == v && f == u) {ans++;break;}}if (i >= ask[u].size())fa[u] = lca[u][0];}int main() {int i, u, v;while (~scanf("%d%d", &n, &m)) {for (i = 1; i <= n; i++) {ask[i].clear();tree[i].clear();dep[i] = 0;fa[i] = i;}for (i = 1; i < n; i++) {scanf("%d%d", &u, &v);tree[u].push_back(v);tree[v].push_back(u);}dfs(1, 1);for (i = 1; i <= m; i++) {scanf("%d%d", &u, &v);ask[getlca(u, v)].push_back(mp(u,v));}ans = 0;solve(1, 1);printf("%d\n", ans);}return 0;}
0 1
- HDU 4912 Paths on the tree
- hdu 4912 Paths on the tree
- hdu 4912Paths on the tree (LCA)
- HDU-4912-Paths on the tree
- HDU 4912 Paths on the tree LCA 排序贪心
- hdu 4912 Paths on the tree(lca+贪心)
- hdu 4912 Paths on the tree lca+贪心
- hdu 4912 Paths on the tree LCA + 贪心
- HDU 4912 - Paths on the tree (LCA 贪心)
- hdu 4912 Paths on the tree (LCA+贪心)
- HDU 4912 Paths on the tree (LCA+贪心)
- HDU 4912 Paths on the tree 贪心+lca
- hdu 4912 Paths on the tree(树链剖分+贪心)
- 【HDU】4912 Paths on the tree 离线LCA+贪心
- HDU 4912(Paths on the tree-树上取链,贪心)
- HDU 4912 Paths on the tree(LCA+贪心)
- hdu4912 Paths on the tree --- LCA贪心
- ZOJ 3863Paths on the Tree
- android驱动开发之介绍
- Unix网络编程(二)套接字地址结构常用函数
- JSTL实现分页
- mybatis学习笔记四(与spring3集成)
- jdbc连接mysql数据库
- HDU 4912 Paths on the tree
- 基于asmack开发的Android开源IM客户端
- ACdream 1156_LCP SUM
- mybatis学习笔记五(与springMVC的集成)
- webuploader上传文件插件
- Linux内核——中断机制
- 黑马程序员之java学习笔记15
- 19 个 Android 开发工具
- virsh命令管理虚拟机