Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Pair{
- int ff;
- int ss;
- public Pair(int f,int s) {
- ff = f;
- ss = s;
- }
- }
- class CustomSort implements Comparator<Pair>{
- @Override
- public int compare(Pair a, Pair b) {
- if(a.ss!=b.ss) {
- return b.ss-a.ss;
- }
- return b.ff-a.ff;
- }
- }
- public class Solution {
- static Scanner sc = new Scanner(System.in);
- public static void dfsUtil(ArrayList<Integer>[] A,int src,int par,int[] citiesCanBeVisited) {
- int ans = 0;
- for(int i : A[src]) {
- if(i!=par) {
- dfsUtil(A,i,src,citiesCanBeVisited);
- ans+=(citiesCanBeVisited[i]+1);
- }
- }
- citiesCanBeVisited[src] = ans;
- }
- public static ArrayList<Integer> orderProsperity(int N, ArrayList<Integer>[] A){
- ArrayList<Integer> result = new ArrayList<>();
- int[] citiesVisited = new int[N+1];
- for(int i=0;i<=N;i++) {
- citiesVisited[i] = -1;
- }
- Queue<Integer> q = new LinkedList<>();
- q.add(1);
- citiesVisited[1] = 0;
- while(!q.isEmpty()) {
- int temp = q.remove();
- for(int i : A[temp]) {
- if(citiesVisited[i] == -1) {
- citiesVisited[i] = citiesVisited[temp]+1;
- q.add(i);
- }
- }
- }
- int[] citiesCanBeVisited = new int[N+1];
- for(int i=0;i<=N;i++) {
- citiesCanBeVisited[i] = 0;
- }
- dfsUtil(A,1,-1,citiesCanBeVisited);
- ArrayList<Pair> dummy = new ArrayList<>();
- for(int i=1;i<=N;i++) {
- dummy.add(new Pair(i,citiesCanBeVisited[i] * citiesVisited[i]));
- }
- Collections.sort(dummy, new CustomSort());
- for(Pair i : dummy) {
- result.add(i.ff);
- }
- return result;
- }
- public static void main(String[] args) {
- int N;
- N = sc.nextInt();
- ArrayList<Integer>[] A = new ArrayList[N+1];
- for(int i=0;i<=N;i++) A[i] = new ArrayList<>();
- for(int i=0;i<N-1;i++) {
- int temp1 = sc.nextInt();
- int temp2 = sc.nextInt();
- A[temp1].add(temp2);
- A[temp2].add(temp1);
- }
- ArrayList<Integer> result= orderProsperity(N,A);
- for(int i : result) {
- System.out.print(i + " ");
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement