当前位置:   article > 正文

codeforces 700B_codeforces - 700b

codeforces - 700b

  1. #include<bits/stdc++.h>
  2. typedef long long LL;
  3. using namespace std;
  4. class Solution{
  5. vector<vector<int> > tr;
  6. vector<int> vi,cnt;
  7. int n,m;
  8. LL ret;
  9. public:
  10. void init(){
  11. cin>>n>>m;
  12. tr = vector<vector<int> >(n+1);
  13. vi = cnt = vector<int> (n+1,0);
  14. for(int i=0;i<2*m;i++){
  15. int x;
  16. cin>>x;
  17. vi[x] = 1;
  18. }
  19. for(int i=1;i<n;i++){
  20. int x,y;
  21. cin>>x>>y;
  22. tr[x].push_back(y);
  23. tr[y].push_back(x);
  24. }
  25. }
  26. void dfs(int st,int f){
  27. cnt[st] = vi[st];
  28. for(int i=0;i<(int)tr[st].size();i++){
  29. int to = tr[st][i];
  30. if(to==f) continue;
  31. dfs(to,st);
  32. ret += min(cnt[to],2*m-cnt[to]);
  33. cnt[st]+=cnt[to];
  34. }
  35. }
  36. void solve(){
  37. ret = 0;
  38. dfs(1,-1);
  39. cout<<ret<<endl;
  40. }
  41. };
  42. int main(){
  43. ios_base::sync_with_stdio(0);
  44. Solution * sol = new Solution();
  45. sol->init();
  46. sol->solve();
  47. return 0;
  48. }

题意:给出一棵树上的2*k个节点,给他们配对,使得他们之间的距离和最大。

题解:可以证明任何一条边最多被这个边左右两棵子树中指定节点数的较小值的边经过。知道这个性质之后就很简单了,枚举边、统计。



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/71337?site
推荐阅读
相关标签
  

闽ICP备14008679号