思路有两种思路,局部连通图通过DFS能做,用并查集也能做,这里用了局部连通图,感觉写的太冗余了,改天再写一个并查集实现。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Main{
static private void mapPut(String name, int time) {
nameList.compute(name, (key,v) -> {
if(v == null) return 0;
return v + time;
});
indexList.computeIfAbsent(name, (key)-> {
return index++;
});
}
static void DFS(int i, HashSet<Integer> set) {
visited[i] = true;
set.add(i);
for(int k = 0; k < num; k++) {
if(!visited[k] && map[i][k] != 0) {
DFS(k,set);
}
}
}
static HashMap<String, Integer> nameList = new HashMap<>(), indexList = new HashMap<>();
static int index = 0, maxNum, num;
static int[][] map;
static boolean[] visited;
static String[] peoples;
static int[] w;
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] in = bf.readLine().split(" ");
int n = Integer.parseInt(in[0]);
int k = Integer.parseInt(in[1]);
maxNum = 2*n;
map = new int[maxNum][maxNum];
visited = new boolean[maxNum];
w = new int [maxNum];
peoples = new String[maxNum];
for(int i = 0; i < n; i++) {
in = bf.readLine().split(" ");
int time = Integer.parseInt(in[2]);
mapPut(in[0], time);
mapPut(in[1], time);
int index1 = indexList.get(in[0]);
int index2 = indexList.get(in[1]);
map[index1][index2] += time;
map[index2][index1] += time;
peoples[index1] = in[0];
peoples[index2] = in[1];
w[index1] += time;
w[index2] += time;
}
num = nameList.size();
ArrayList<HashSet<Integer>> gangList = new ArrayList<>();
for(int i = 0; i < num; i++) {
HashSet<Integer> set = new HashSet<>();
DFS(i,set);
gangList.add(set);
}
int count = 0;
HashMap<String, Integer> res = new HashMap<>();
for(HashSet<Integer> set : gangList) {
if(set.size() <= 2)continue;
int max = -1;
int sum = 0;
for(int i : set) {
int wi = w[i];
sum += wi;
if(max == -1 || wi > w[max]) {
max = i;
}
}
if(sum/2 <= k)continue;
count++;
res.put(peoples[max], set.size());
}
System.out.println(count);
if(count != 0) {
Set<String> set = res.keySet();
Object[] objs = set.toArray();
Arrays.sort(objs);
for(Object o : objs) {
System.out.println(o + " " + res.get(o));
}
}
}
}