Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Version de la solution F optimisé #22

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions contest/f_goodies/input/input31.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
20
30
3 5 11 14 12 6 10 7 5 6 5 3 3 5 11 6 4 3 13 12 2 12 3 12 4 2 8 12 9 10
50
27
1 1 2 2 3 3 3 4 4 5 5 6 6 7 8 9 9 10 10 11 12 12 13 13 14 14 14
52 changes: 52 additions & 0 deletions contest/f_goodies/sol/f_goodies_optimized.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Solution by ArnaudF
# Largely inspired by the solution from Sebastien Goll & Louis Hasenfratz
import collections
from collections import defaultdict

Q = int(input())
N = int(input())
# The goodies are sorted to make sure that two goodies of the same price are grouped together.
# This is useful when constructing combinations, line 27-29.
goodies = sorted(list(map(int, input().split())))

#Sac definition
bag = defaultdict(set)
bag[0].add(tuple())

#List substration. Does the same as the - operator with sets.
# list1 = [1,2,3,4,5]; list2 = [4,5]
# Return: [1,2,3]
def diff(list1, list2):
for element in list2:
list1.remove(element)
return list1

#Build all the possible combinations that give a bag size from 0 to Q.
for card in goodies:
for size in range(Q+1, -1 , -1):
if size + card <= Q and size in bag:
for combinaison in bag[size]:
combinaison = combinaison + (card,)
bag[size+card].add(combinaison)

#For each combination that gives the desired sum Q,
# the combination is removed from the goodies list.
# Then we check whether it is still possible to build a bag with a price Q.
# If not: We win, print "OUI"
weWin = False
for combinaison in bag[Q]:
newgoodiesList = diff(goodies.copy(), combinaison)
newbag = defaultdict(bool)
newbag[0] = True
for card in newgoodiesList:
for size in range(Q+1, -1 , -1):
if size + card <= Q and size in newbag:
newbag[size+card] = True
if Q not in newbag:
weWin = True
break

if weWin:
print("OUI")
else:
print("NON")