算法与数据结构之贪心算法

06 Sep 2018

Categories: 算法与数据结构

Question 1

import sys
def get_change(m):
    #write your code here
    n10 = m//10
    n5 = (m%10)//5
    n1 = (m%10)%5
    return n1+n5+n10
### run
if __name__ == '__main__':
    m = int(sys.stdin.read())
    print(get_change(m))

Question 2

import sys
def get_optimal_value(capacity, weights, values):
    value = 0.
    # write your code here
    temp = [(w,v/w) for w,v in zip(weights, values)]
    temp = sorted(temp, key=lambda s:s[1], reverse=True)
    remain = capacity
    for i in range(len(temp)):
    	if remain==0: break
    	w_in = min(remain, temp[i][0])
    	remain -= w_in
    	value += w_in*temp[i][1]
    return value

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value))

Question 3

import sys
def max_dot_product(a, b):
    #write your code here
    return sum([x*y for x,y in zip(sorted(a),sorted(b))])

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    n = data[0]
    a = data[1:(n + 1)]
    b = data[(n + 1):]
    print(max_dot_product(a, b))

Question 4

import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
    points = []
    #write your code here
    segments = sorted(segments, key=lambda s: s.end)
    points.append(segments[0].end)
    for s in segments:
        if s.start>points[-1]:
            points.append(s.end)
    return points

if __name__ == '__main__':
    input = sys.stdin.read()
    n, *data = map(int, input.split())
    segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
    points = optimal_points(segments)
    print(len(points))
    for p in points:
        print(p, end=' ')

Question 5

import sys
def optimal_summands(n):
    summands = []
    #write your code here
    remain = n
    for i in range(1,n+1):
        last_c = i if remain-i>i else remain
        summands.append(last_c)
        remain -= last_c
        if remain==0: break
    return summands

if __name__ == '__main__':
    input = sys.stdin.read()
    n = int(input)
    summands = optimal_summands(n)
    print(len(summands))
    for x in summands:
        print(x, end=' ')

Question 6

import sys
from functools import cmp_to_key

def comp(a,b):
    if a[0]>b[0]:
        return 1
    elif a[0]<b[0]:
        return -1
    else:
        ab = a+b
        ba = b+a
        return 1 if ab>ba else -1 if ab<ba else 0

def largest_number(a):
    #write your code here
    a = sorted(a, key=cmp_to_key(comp), reverse=True)
    return ''.join(a)

if __name__ == '__main__':
    input = sys.stdin.read()
    data = input.split()
    a = data[1:]
    print(largest_number(a))