//考完试才做出来,自己写了几个例子试了一下是对的,不知道有没有更高效的思路 import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Main {     static class Result{         int back;         int notback;         public Result(int back,int notback){             this.back = back;             this.notback = notback;         }     }          static class Pair{         int p1,p2;         public boolean contains(int s){             return p1==s||p2==s;         }         public Pair(int p1,int p2){             this.p1 = p1;             this.p2 = p2;         }         public int another(int p){             if (p==p1){                 return p2;             }else return p1;         }     }     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         int n = s.nextInt();         s.nextLine();         Set<Pair> pool = new HashSet<Pair>();         for (int i=0;i<n-1;i++){             String[] temp = s.nextLine().split(" ");             pool.add(new Pair(Integer.parseInt(temp[0]),Integer.parseInt(temp[1])));         }         //System.out.println(pool.size());         System.out.println(func(1,pool).notback);                       }     private static Result func(int i, Set<Pair> pool) {         Set<Pair> connted = connected(pool,i);         if (connted.size()==0){             //System.out.println(i+","+"0,0");             return new Result(0,0);         }         pool.removeAll(connted);         int m =0,n=0;         List<Result> results = new ArrayList<Result>();         for (Pair p:connted){             int v = p.another(i);             Result r = func(v,pool);             results.add(r);         }         int max = 0;         for (Result result:results){             m += result.back + 2;             if (result.back-result.notback>max){                 max = result.back-result.notback;             }         }         n = m -max  -1;         //System.out.println(i+","+m+","+n);         return new Result(m,n);     }          private static Set<Pair> connected(Set<Pair> pool,int target){         Set<Pair> ret = new HashSet<Pair>();         for (Pair p:pool){             if (p.contains(target)){                 ret.add(p);             }         }         return ret;              } }
点赞 1

相关推荐

不愿透露姓名的神秘牛友
昨天 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
牛客网
牛客企业服务