Java题解,含详细注释 | 核心:状态压缩

隐匿社交网络

https://www.nowcoder.com/practice/2870f9db6aeb4eb08fbd6460397f9bf4

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    public static int merge(Map<Long, Integer> map) {
        for (Map.Entry<Long, Integer> i : map.entrySet()) {
            for (Map.Entry<Long, Integer> j : map.entrySet()) {
                if (!i.getKey().equals(j.getKey()) && (i.getKey() & j.getKey()) >= 1) {
                    int tmp = i.getValue() + j.getValue();
                    long tmpV = i.getKey() | j.getKey();
                    map.remove(i.getKey());
                    map.remove(j.getKey());
                    map.merge(tmpV, tmp, Integer::sum);
                    return 1;
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        while (T-- > 0) {
            int n = in.nextInt();
            //map的key是这个网络的状态,value是网络成员数;(一个数 & key) >= 1则加到该网络
            Map<Long, Integer> map = new HashMap<>();
            for (int i = 0; i < n; i++) {
                long x = in.nextLong(), flag = 0;
                for (Map.Entry<Long, Integer> en : map.entrySet()) {
                    if ((en.getKey() & x) >= 1) {
                        //x加入某个网络
                        Integer value = en.getValue();
                        map.remove(en.getKey());
                        map.merge(en.getKey() | x, value + 1, Integer::sum);
                        flag = 1;
                        break;
                    }
                }
                //如果x没有加到其它网络,则自己创建一个
                if (flag == 0) map.merge(x,1, Integer::sum);
            }
            //循环合并网络,网路是按位压缩枚举的,所以数量不会超过20个
            while (merge(map) == 1) ;
            int ans = 0;
            for (Integer j : map.values()) ans = Math.max(ans, j);
            System.out.println(ans);
        }
        in.close();
    }
}

全部评论

相关推荐

07-11 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务