• HackerRank


    Not hard, but with some amount of coding. Brutal-force would work: iterate each unique pair of points. And I used "y=ax+b" to check each point which side it resides.

    import math
    
    EPSI = 0.00000001
    
    # y = ax + b            
    def calcAB(p0, p1):
        if (p0[1] == p1[1]):
            return 0, p0[1]
        a = (p0[1] - p1[1])/(p0[0] - p1[0])
        b = p0[1] - a * (p0[0])
        return a, b
                
    def splitPV(coords, ws, xs, wpp, ni, nj):
        left = right = 0        
        for i in range(len(ws)):
            if (i == ni or i == nj): continue
            p = coords[i]
            w = ws[i]
            if (p[0] < xs):
                left += w
            elif (p[0] > xs):
                right += w
                
        if (left < right):
            left += wpp
        else:
            right += wpp    
        return abs(left - right), min(left, right)    
        
    def splitP(coords, vs, ca, cb, wpp, ni, nj):    
        left = right = 0
        for i in range(len(ws)):
            if (i == ni or i == nj): continue
            p = coords[i]
            w = ws[i]
            func_v = p[0] * ca + cb        
            if (func_v < p[1]):
                left += w
            elif (func_v > p[1]):
                right += w
                
        if (left < right):
            left += wpp
        else:
            right += wpp    
        return abs(left - right), min(left, right)
        
    # Get Input            
    coords = []
    ws = []
    n = int(input())
    for _ in range(n):
        x, y, w = map(int, input().split())
        coords.append([x, y])
        ws.append(w)
    
    # Brutal Force
    diff = 99999999999999
    minw = 0
    plen = len(ws)
    for i in range(plen):
        for j in range(i + 1, plen):        
            p0 = coords[i]
            p1 = coords[j]        
            wpp = ws[i] + ws[j]
            
            min_diff = minw = 0
            # Case 1: vertical
            if (abs(p0[0]-p1[0]) <= EPSI):
                xs = p0[0]
                min_diff, minw = splitPV(coords, ws, xs, wpp, i, j)
            # Case 2: any other
            else:
                a, b = calcAB(p0, p1)
                min_diff, minw = splitP(coords, ws, a, b, wpp, i, j)
            
            if (min_diff < diff):
                diff = min_diff
                grp = minw
    
    print (grp)
  • 相关阅读:
    03、SqlMapConfig.xml配置文件
    02、Mybatis整体架构介绍
    01、Mybatis快速入门
    Struts2学习笔记(十一)——文件上传
    Struts2学习笔记(十)——自定义拦截器
    Struts2学习笔记(九)——数据校验
    Struts2学习笔记(八)——国际化
    Struts2学习笔记(七)——类型转换
    Struts2学习笔记(六)——Action处理请求参数
    Struts2学习笔记(五)——Action访问Servlet API
  • 原文地址:https://www.cnblogs.com/tonix/p/4553611.html
Copyright © 2020-2023  润新知