Which upgrade wins

A program spends its time in several parts, such as computing, waiting for memory and waiting for a disk. You can pay for one upgrade, each of which speeds up just one part. Amdahl's law tells you which is worth it.

What to build

A program that works out the new run time and the overall speedup for each upgrade, then names the best one.

Requirements

  • The run time is split into categories, each with its time in seconds.
  • An upgrade names a category and a factor f: that category becomes f times faster, and all the others stay the same.
  • For every upgrade print name total speedup, with the new total time and the speedup both to 3 decimal places, in the input order.
  • Finish with best NAME for the upgrade with the largest speedup (the first one on a tie).

Input

A line with n, then n lines category seconds. Then a line with m, then m lines name category factor. The numbers may be decimals.

Output

m + 1 lines.

Constraints

1 ≤ n ≤ 10; 1 ≤ m ≤ 10; every upgrade names an existing category; factors are above 1.

Example

Input:

3
cpu 60
memory 30
disk 10
3
fastcpu cpu 2
ssd disk 10
ram memory 1.5

Output:

fastcpu 70.000 1.429
ssd 91.000 1.099
ram 90.000 1.111
best fastcpu

Why it works

Amdahl's law in plain terms: only the time spent in the improved category shrinks, so a huge speedup of a small category gains little while a modest speedup of the biggest category can win.

Examples

Example 1 · Input
3
cpu 60
memory 30
disk 10
3
fastcpu cpu 2
ssd disk 10
ram memory 1.5
Expected output
fastcpu 70.000 1.429
ssd 91.000 1.099
ram 90.000 1.111
best fastcpu
Example 2 · Input
2
compute 10
io 90
2
gpu compute 100
cache io 2
Expected output
gpu 90.100 1.110
cache 55.000 1.818
best cache

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The total time is the sum of the category times. An upgrade changes only its own category: new total = total − t + t ÷ factor.

Hint 2

Speedup = old total ÷ new total. Compare the speedups to choose the best.

Hint 3

On a tie keep the first upgrade in the input.

Solution

Show one correct solution (try it yourself first)
n = int(input())
times, total = {}, 0.0
for _ in range(n):
    c, t = input().split()
    times[c] = float(t)
    total += float(t)
m = int(input())
best_name, best = "", 0.0
for _ in range(m):
    name, cat, f = input().split()
    t = times[cat]
    new_total = total - t + t / float(f)
    speedup = total / new_total
    print(name, f"{new_total:.3f}", f"{speedup:.3f}")
    if speedup > best + 1e-12:
        best, best_name = speedup, name
print("best", best_name)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Measuring performance →