1034 Head of a Gang (30 分) java 实现

思路有两种思路,局部连通图通过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));
			}
		}
	}

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值