Easy Max

作者: 抬头挺胸才算活着 | 来源:发表于2021-08-05 21:00 被阅读0次

题目

已知有一些点,以及各个点之间的边权值(无向边).现在要将这些点分成两个集合,并且要求两个集合之间点的权值和最大 比如有三个点编号为1,2,3 其中12之间权值为50,23之间权值为40,13之间权值为30. 那么分成(1,3)和(2)两个集合,他们之间权值和为40+50=90为最大 (点的编号从1开始)

示例

解法

package com.company;

import java.util.Scanner;

public class OJ149 {
    // https://oj.rnd.huawei.com/discuss/problems/discussions/533f0073-25be-4f90-a5dc-39d931e62872?navName=python%20%E9%80%92%E5%BD%92%E6%90%9C%E7%B4%A2%20900ms
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] matrix = new int[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }

        int result = DFS(1, 0, 1, n, matrix);
        System.out.println(result);
    }

    private static int DFS(int currentNode, int currentSum, int select, int numOfNodes, int[][] matrix) {
        if(currentNode == numOfNodes) {
            return currentSum;
        }

        int selectSum = currentSum, notSelectSum = currentSum;
        for (int i = 0; i < currentNode; i++) {
            if(getBit(select, i)==1) {
                notSelectSum += matrix[i][currentNode];
            }else{
                selectSum += matrix[i][currentNode];
            }
        }

        int sum1 = DFS(currentNode + 1, selectSum, setBit(select, currentNode), numOfNodes, matrix);
        int sum2 = DFS(currentNode + 1, notSelectSum, resetBit(select, currentNode), numOfNodes, matrix);

        return Math.max(sum1, sum2);
    }

    private static int getBit(int select, int i) {
        return (select >> i) % 2;
    }

    private static int setBit(int select, int i) {
        return select | (1<<i);
    }

    private static int resetBit(int select, int i) {
        return select & (~(1<<i));
    }
}

相关文章

  • Easy Max

    题目 已知有一些点,以及各个点之间的边权值(无向边).现在要将这些点分成两个集合,并且要求两个集合之间点的权值和最...

  • 骷髅头也完成了

    首先打开max,这次我们换一种方法制作。用切线在一个平面内勾勒出骷髅结构,就是剪切命令。下面的事情就so easy...

  • 2016.10.26

    Easy easy

  • 2019-04-02

    一文介绍MAX3490CSA MAX3483,MAX3485,MAX3486,MAX3488,MAX3490...

  • “放松”不只是 "Relax",还有哪些说法

    01 、 Take it easy Take it easy 或 take things easy 用来劝他人不要...

  • 其他函数(30个)

    ·统计函数(Max、Min、Average、Large、Small) ·MAX:最大值 MAX( ) =MAX(B...

  • make a plan for 2019

    it is easy to make a plan for the new year, but not easy ...

  • Easy

    人们常说,Take it easy!Make it easy! 有时也会说,A easy guy。那么什么是Eas...

  • Training Counter-Vital life

    This is an easy to use, easy to get started app. It is a ...

  • 简单递推

    1.思路:max[k] = k.val+max(max(k.left),max(k.right)) 注意缓存,...

网友评论

      本文标题:Easy Max

      本文链接:https://www.haomeiwen.com/subject/budvvltx.html