Z
Z
ZykaMyzyka2021-06-13 23:04:55
Python
ZykaMyzyka, 2021-06-13 23:04:55

How to solve this problem in python?

There is a data set consisting of triples of positive integers. It is necessary to choose two numbers from each triple so that the sum of all the chosen numbers is divisible by 4 and at the same time is the maximum possible. It is guaranteed that the required amount can be obtained. The program should print a single number - the maximum possible amount that meets the conditions of the problem. Input
example:
6
8 3 4
4 8 12
9 5 6
2 8 3
12 3 5
1 4 12 amount, and then how lucky)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-06-13
@ZykaMyzyka

Dynamic programming.
F(i,k) is the maximum sum that can be obtained from the first i triples, such that its remainder after dividing by 4 is k.
Base: F(0,0) = 0, F(0,k) = -infinity.
Answer: F(n, 0).
Recalculation

F(i,k) = max(F(i-1, ((k-a[i][0]-a[i][1])%4+4)%4)+a[i][0]+a[i][1], 
             F(i-1, ((k-a[i][1]-a[i][2])%4+4)%4)+a[i][1]+a[i][2], 
             F(i-1, ((k-a[i][0]-a[i][2])%4+4)%4)+a[i][0]+a[i][2])

But instead of -infinity, it’s better to somehow note that the position (i, k) is invalid (you can’t get the sum with the remainder k with the first i triplets. And it’s not necessary to choose invalid options when choosing the maximum.
Also, instead of enumerating all pairs of three elements, it’s better to take the sum three and subtract one, which is looped over.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question