UVALive - 3902 Network 无根树转为有跟树+搜索+贪心
来源:互联网 发布:阿里云解析教程 编辑:程序博客网 时间:2024/04/29 03:42
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=16451
题目大意:n台机器连成一个树状网络,其中叶节点是客户端,其他节点是服务器。现在有一台服务器在节点s,服务器能传播的信号的距离为k,因为有的用户距离服务器的距离大于k,所以必须添加服务器。问最少要添加几个服务器,才能使每个客户端都收到信号
首先以S为根节点建立一颗有根树,并dfs建树时记录点的深度,是否为叶子。
把叶子按深度从大到小排序,每次贪心选一个深度最大的叶子,然后找到他的k级祖先,以k级祖先出发dfs标记K层以内的叶子,如此反复直到叶子都被染色。
复杂度O (N)
#include <cstdio>#include <cmath>#include <cstring>#include <string>#include <algorithm>#include <queue>#include <map>#include <set>#include <vector>#include <iostream>using namespace std;const double pi=acos(-1.0);double eps=0.000001;int n;vector< int >mp[1005];struct node{ int x,v; node(int a=0,int b=0) { x=a,v=b; }};bool cmp(node a,node b){ return a.v>b.v;}node leave[1005]; int s,k;int id=0;int fa[1005];int vis[1005];int isleaf[1005];void dfs1(int x,int dep){ vis[x]=1; if (mp[x].size()==1) { leave[++id]=node(x,dep); isleaf[x]=1; return ; } for (int i=0; i<mp[x].size(); i++) { int v=mp[x][i]; if (vis[v])continue; fa[v]=x; dfs1(v,dep+1); }}int find_fa(int x ){ int tmp=k; while(tmp--) x=fa[x]; return x;}void dfs2(int x,int cur){ if (isleaf[x]) vis[x]=1; for (int i=0;i<mp[x].size();i++) { int v=mp[x][i]; if (vis[v])continue; if (cur>0) dfs2(v,cur-1); }}int main(){ int t; cin>>t; int i,j; int x,y; while(t--) { id=0; cin>>n; cin>>s>>k; for (i=1; i<=n; i++) mp[i].clear(); for (i=1; i<=n-1; i++) { scanf("%d%d",&x,&y); mp[x].push_back(y); mp[y].push_back(x); } memset(vis,0,sizeof vis); memset(isleaf,0,sizeof isleaf); memset(fa,0,sizeof fa); dfs1(s,1); sort(leave+1,leave+1+id,cmp); memset(vis,0,sizeof vis); int ans=0; dfs2(s,k); for (i=1;i<=id;i++) { node tp=leave[i]; if (vis[tp.x])continue; int st=find_fa(tp.x ); ans++; dfs2(st,k); } printf("%d\n",ans); } return 0;}
0 0
- UVALive - 3902 Network 无根树转为有跟树+搜索+贪心
- UVALive - 3902 Network 无根树转为有跟树
- UVALive - 3902 Network
- UVALive 3902 Network
- UVALive - 3902 Network
- uvalive 3971 - Assemble(二分搜索 + 贪心)
- uvalive 3971 - Assemble(二分搜索 + 贪心)
- UVaLive 4731 UVa 1456 - Cellular Network(概率DP 贪心)
- Live Archive 3902 Network 树 贪心
- UVaLive(LA) 3902 Network,Seoul 2007
- UVALive - 4960 Sensor network(生成树+LCA)
- Uva 1267 Network 解题报告(贪心搜索)
- UVALive 3027 Corporative Network
- UVALive 3027 Corporative Network
- UVALive 4731 Cellular Network
- UVALive 4731 Cellular Network
- UVALive 3027 Corporative Network
- UVALive 3027 Corporative Network
- Android Service与Activity之间通信使用Messenger方式
- Unity3d 和 3dmax轴向问题以及快速解决方案
- 虚函数调用
- Linux中的15个‘echo’ 命令实例
- Java transient关键字使用小记
- UVALive - 3902 Network 无根树转为有跟树+搜索+贪心
- xapp1052之dma_test.v
- redis集群搭建手册
- 对于三星手机的手工root方法
- Collection List Set Map 区别记忆
- Linux -- 安装配置Android SDK
- java post 上传文件 common-fileupload
- 将博客搬至CSDN
- 程序员必看的十大电影