https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem= 2515
Http://7xjob4.com1.z0.glb.clouddn.com/c6a2a6f54f5a6c2cae2c82df2ec552f7
Test instructions: To the network Diagram, the leaf node is the client, the other is the server, set the minimum number of services on the server so that the client-to-service distance does not exceed the specified value
Idea: The existing service as the root, convert the map to a root tree, record the depth of each leaf node; Select the maximum value of the leaf node at the specified distance from the parent node as the most cost-effective setting service, after setting the DFS overwrite state, only need to handle the leaf nodes with a depth greater than the specified value.
1#include <bits/stdc++.h>2 using namespacestd;3 4 Const intmaxn=1005;5Vector <int>GR[MAXN],NODES[MAXN];6 intN,S,K,FA[MAXN];7 BOOLCOVERED[MAXN];8 9 voidDfsintUintFintd)Ten { One     inti,j; Afa[u]=F; -     intNc=gr[u].size (); -     if(nc==1&& d>k) the     { - nodes[d].push_back (u); -     } -      for(i=0; i<nc;i++) +     { -         intv=Gr[u][i]; +         if(v!=f) ADFS (v,u,d+1); at     } -     return ; - } -  - voidDFS2 (intUintFintd) - { in     inti,j; -covered[u]=true; to     intNc=gr[u].size (); +      for(i=0; i<nc;i++) -     { the         intv=Gr[u][i]; *         if(V!=f && d<k) $DFS2 (v,u,d+1);Panax Notoginseng     } -     return ; the } +  A intSolve () the { +     intans=0; -     inti,j; $memset (Covered,0,sizeof(covered)); $      for(intd=n-1;d >k;d--) -     { -          for(i=0; I<nodes[d].size (); i++) the         { -             intu=Nodes[d][i];Wuyi             if(Covered[u])Continue; the  -             intv=u; Wu              for(j=0; j<k;j++) -v=Fa[v]; AboutDFS2 (v,-1,0); $ans++; -         } -     } -     returnans; A } +  the  - intMain () $ { the     intT; the     inti,j; thescanf"%d",&T); the      while(t--) -     { inscanf"%d%d%d",&n,&s,&k); the          for(i=0; i<=n;i++) the         { About gr[i].clear (); the nodes[i].clear (); the         } the          for(i=1; i<n;i++) +         { -             intu,v; thescanf"%d%d",&u,&v);Bayi Gr[u].push_back (v); the gr[v].push_back (u); the         } -DFS (s,-1,0); -printf"%d\n", Solve ()); the     } the     return 0; the}View Code
Uvalive 3902 Network