Предмет: Информатика, автор: Juliaaaaaa6

Даны цело численный массив А [1: n] и число М. Найти множество элементов А [i1], А [i2], ..., А [ik] (1< i1 < ... < ik < n), что А [i1] + А [i2] + ... А [ik] = М.

Ответы

Автор ответа: StSerg
0
описание алгоритма: задан список А и число M, n = len(A). для того чтобы найти все возможные варианты выборки из А необходимо построить множество двоичных чисел от 1 до 2^n-1 и складывать только те индексы разряд которого которого в двоичном числе равен 1, т.е. для двоичного числа 1100 это будут индексы 2 и 3.
Если сумма будет равна М вывести последовательность индексов, иначе идем далее
Язык Python
A=[21,4,5,4,32] #Задание массива А
M = 9             #Задание М
for i in range(1, 2**len(A)-1): # для всех i от 1 до 2^n-1
  ind = []                             # список индексов используемых в данной итерации
  cnt = 0                             # сумма элементов А
  for j in range(len(A)):          # для всех j от 0 до n
    if i&2**j:                          # Если индекс есть в бинарной записи i, то
      cnt += A[j]                    # прибавить к сумме A[j]
      ind.append(str(j))                 # запомнить индекс
      if cnt > M: break            # если сумма больше M выходим из цикла
  if cnt == M:                       # если сумма равна M
    print ', '.join(ind)               # печатаем список эффективных индексов

для данной программы будет выдано две строки
1,2
2,3
Похожие вопросы
Предмет: Английский язык, автор: sshopa97
30 БАЛОВ!
I. Choose the odd word out.

1.ordinary,typical,incredible,usual

2.comedy,mystery,science fiction, novel

3.spiky,wavy,middle aged, curly

4.plump,slim,freckles,well-build

II. Put the verbs into the Present Simple, Present Continuous, Past Simple, Past Continuous.

1.I …..( study) in my bedroom at the moment, but I can join you in the park later.

2.Tom ……..(watch)TV when Jane arrived.

3.Water………..(not, boil) at 80C.

4.The policeman asked, «What………(you, do) at the time of the robbery?»

III. Fill in: why, who, whose, where, which, when.

1.A doctor is someone……..helps sick people.

2.Do you know……book this is?

3. It was summer time……we decided to go on holiday to New York.

4. Tom is very reliable. That’s……I like him.

IV. Complete the sentences using in ,out, up, on, with, into.

1. John gave……boxing two years ago because of a bad injury.

2. That blouse goes really well……your skirt.

3. I ran…….an old friend at the supermarket yesterday.

4. Go…… I’m listening to you.

V. Choose the correct response.

1.What’s your sister like?

a) She is tall with freckles. b) She is very sociable.

2.What’s the best way to avoid pickpockets?

a) Don’t be so silly. b) You should look after your wallet.

3. I’ve got some good news.

a) That’s amazing! b) Sure

4. I need to get more exercise.

a) Why don’t you go home b) How about joining a gym?

VI. Read the text and answer the questions.

Help Hearts

On 20th August, a ‘Help Hearts’ charity event took place in the town of Whitefall. A group of nurses from one of the local hospitals came up with the idea and over 1000 people of all ages took part.

Luckily, it was a sunny day. Everyone had fun either swimming, walking or windsurfing. Thanks to the event, 5000$ was raised for the charity.

Bob Keene, one of the people who organized the event , said,’ We wanted to do something useful for others and this seemed the most fun thing to do.

The hospital administrators were so proud, they decided to make the event part of the hospital’s yearly calendar.

1. What was the name of the organizations that raised the money?

2. Who planned the event?

3. How many people took part?

4. What was the weather like during the event?

5. What happened as result of the event
Предмет: Физика, автор: Милана5578