zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    拉姆达表达式(lambda Expressions)
    Func,Action 的介绍
    VS2012 此模板尝试加载组件程序集”NuGet.VisualStudio.interop,Version=1.0.0.0 的解决
    444 英语口语
    Base algorithm
    Windows Search Service
    Windows Azure Storage
    HDU 3395 Special Fish
    CodeForces 235B Let's Play Osu!
    HDU 3435 A new Graph Game
  • 原文地址:https://www.cnblogs.com/tonix/p/4553611.html
Copyright © 2011-2022 走看看