Most Popular Friend - Problems | CodeChef
public class Main {
static final PrintWriter pw =
new PrintWriter(new OutputStreamWriter(System.out), true);
static final FastReader reader = new FastReader();
public static void main(String[] args){
int num = reader.nextInt();
for(int i=0;i<num;i++) {
int n = reader.nextInt();
List<List<Integer>> list = new ArrayList<>();
for(int j=0;j<n;j++) {
String input = reader.nextLine();
list.add(new ArrayList<>());
for(int data : split(input)) {
list.get(j).add(data - 1);
}
}
long min = Long.MAX_VALUE;
int id = -1;
for(int j=0;j<n;j++) {
long totalDist = 0;
HashSet<Integer> visited = new HashSet<>();
Queue<BfsObj> q = new LinkedList<>();
q.add(new BfsObj(j, 0));
visited.add(j); // visited j
while(!q.isEmpty()) {
BfsObj curr = q.peek();
q.remove();
for(int next : list.get(curr.id)) {
if(!visited.contains(next)) {
q.add(new BfsObj(next, curr.dist + 1));
visited.add(next);
totalDist += (curr.dist + 1);
}
}
}
if(min > totalDist) {
min = totalDist;
id = j;
}
}
System.out.println((id + 1) + " " + String.format("%.6f",
((double)min / n)));
}
}
public static int[] split(String input) {
String[] data = input.split(" ");
int[] list = new int[data.length];
for(int i=0;i<data.length;i++) {
list[i] = Integer.parseInt(data[i]);
}
return list;
}
}
class BfsObj{
public final int id;
public final int dist;
public BfsObj(int id, int dist) {
this.id = id;
this.dist = dist;
}
}
Có cách nào cải thiện bfs của em không ạ? Hay bfs của em bị sai ở đâu? Hệ thống chấm TLE 0.5s.