0
点赞
收藏
分享

微信扫一扫

C++二分算法的应用:寻找峰值原理、源码及测试用例

1. 1402 做菜顺序

题目详细为:

示例为:

提示:

难度:【困难

算法思路:
由于n的取值并没有很大,所以使用暴力解法解决这题完全没有问题,但是个人觉得可以这样来实现。
可以分为三类情况,(1)satisfaction这个数组(列表)中的最大数小于零,这样得到最终结果(按照上述公式)肯定小于0,那么直接返回0即可;(2)satisfaction这个数组(列表)中的最小数大于零,对这个数组进行升序排序,然后利用上述公式计算返回即可;(3)satisfaction这个数组(列表)中同时存在小于0和大于0的数,首先对这个数组进行升序排序,然后用一个变量根据上述公式计算对应结果num2,用变量num存储数组的和,之后再遍历这个数组,变量ans(初始值为0)返回最终结果,执行下述操作即可,ans = max(ans,num2),num2 -= num,num -= satisfaction[i],示意图如下:


satisfaction数组
排序前  [-1,-8,0,5,-9]
排序后 [-9,-8,-1,0,5]
num的值为:-13
num2的值为:-9 * 1 + -8 * 2 + -1 * 3 + 0 * 4 + 5 * 5 =  -3
ans = 0
遍历次数 ans num num2
1 0 -13 -3
2 0 -4 10
3 10 4 14
4 14 5 10
5 14 5 5

参考代码如下:

class Solution(object):
    def maxSatisfaction(self, satisfaction):
        """
        :type satisfaction: List[int]
        :rtype: int
        """
        satisfaction.sort()
        if satisfaction[-1] < 0:
            return 0

        ans = 0
        n = len(satisfaction)
        if satisfaction[0] > 0:
            start = 1
            for e in satisfaction:
                ans += start * e
                start += 1
        else:
            num = sum(satisfaction)
            num2 = 0
            for i in range(n):
                num2 += satisfaction[i] * (i+1)
            for i in range(n):
                ans = max(ans,num2)
                num2 -= num
                num -= satisfaction[i]

        return ans


a = Solution()
print(a.maxSatisfaction(satisfaction = [-1,-8,0,5,-9]))

运行结果:
请添加图片描述
虽然算法效率总体还不怎么的,但是比暴力肯定要好一些。

2. 2316. 统计无向图中无法互相到达点对数

题目详细为:

示例为:

提示:

算法思路:
从0号节点依次遍历到n-1号节点,如果遍历到某节点时,在map中已经存在了,那么不需要再进行接下来的操作,否则,在map中记录当前节点,然后依次遍历与该节点连通的节点,继续上述操作,直到遍历完某节点所有连通的节点,此时map中存储的节点个数减去pre(初始为0),即可得到一组不为0数,用一个数组arr存储,直到所有节点全部遍历完,然后计算arr中的数即可得到最终结果。但是有问题遍历arr需要两层,应该提交不了,为此直接在遍历节点的同时计算最终结果(但是最终还是差几个用例没有通过,最后参考官方代码改进才通过)。

参考代码为:

class Solution(object):
    def countPairs(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: int
        """
        map = {}
        for e in range(n):
            map[e] = []
        for key,value in edges:
            map[key].append(value)
            map[value].append(key)

        map2 = {}

        def dfs(cur_node):
            map2[cur_node] = 1
            arr = map[cur_node]
            count = 1
            for e in arr:
                if not map2.get(e,None):
                    count += dfs(e)
            return count

        ans = 0
        pre = 0
        for i in range(n):
            if not map2.get(i,None):
                count = dfs(i)
                ans += pre * count
                pre += count

        return ans

运行结果:
请添加图片描述

举报

相关推荐

寻找峰值--二分

0 条评论