图的遍历, 美团笔试题

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n =sc.nextInt();
        List<Integer>[] g = new ArrayList[n+1];
        for(int i=1; i <= n; i++) {
            g[i] = new ArrayList<Integer>();
        }
        for(int i=1; i < n; i++) {
            int a = sc.nextInt(), b = sc.nextInt();
            g[a].add(b); g[b].add(a);
        }
        int pathLen = 0;
        boolean[] used = new boolean[n+1];
        Queue<Integer> q = new LinkedList<>();
        q.offer(1); used[1] = true;
        while(!q.isEmpty()) {
            int size = q.size();
            pathLen ++;
            for(int i=0; i < size; i++) {
                int cur = q.poll();
                for(int j=0; j < g[cur].size(); j++) {
                    int x = g[cur].get(j);
                    if(used[x] == false) {
                        used[x] = true;
                        q.offer(x);
                    }
                }
            }
        } 
        System.out.println(2*(n-1)-(pathLen-1));
    }
}


猜你喜欢

转载自www.cnblogs.com/lixyuan/p/13187245.html