Вопрос задан 28.07.2018 в 23:17. Предмет Информатика. Спрашивает Маяковский Максим.

Задача по информатике. Pascal или Delphi с подробным решением и объяснениями! Банкомат В некотором

государстве в обращении находятся банкноты определенных номиналов. Национальный банк хочет, чтобы банкомат выдавал любую запрошенную сумму при помощи минимального числа банкнот, считая, что запас банкнот каж дого номинала неограничен. Помогите Национальному банку решить эту задачу. Входные данные Первая строка входных данных содержит натуральное число N не превосходящее 100 — количество номиналов банкнот в обращении. Вторая строка входных данных содержит N различных натуральных чисел x1, x2, ..., xN, не превосходящих 106 — номиналы банкнот. Третья строчка содержит натуральное число S, не превосходящее 106 —сумму, которую необходимо выдать. Выходные данные Программа должна найти представление числа S виде суммы слагаемых из множества xi, содержащее минимальное число слагаемых и вывести это представление на экран (в виде последовательности чисел, разделенных пробелами). Если таких представлений существует несколько, то программа должна вывести любое (одно) из них. Если такое представление не существует, то программа должна вывести строку No solution. Примеры входные данные 5 1 3 7 12 32 40 выходные данные 32 7 1
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Натарова Полина.
Var v:array [0..100000] of integer;    a:array [0..100,0..100000] of integer;    m,p,k,w:integer;
procedure step(z,ma:integer);beginif z>0 then       if a[z,ma]<>a[z-1,ma] then                             if a[z-1,ma]<a[z-1,ma-v[z]]+v[z] then                                                              begin step(z-1,ma-v[z]);                                                                    write(v[z],' ');                                                              end                                                              else step(z-1,ma)                                                              else step(z-1,ma); end;

beginread(k);for p:=1 to k do begin   read(v[p]);   end;read(w);for p:=1 to k do begin   for m:=1 to w do begin      if m-v[p]>=0 then a[p,m]:=(max(a[p-1,m-v[p]]+v[p],a[p-1,m]))                   else a[p,m]:=a[p-1,m];      end;      end;if a[k,w]=w then step(k,w)            else writeln('No solution');end.
0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

To solve this problem, we need to find the minimum number of banknotes that can be used to represent a given sum. Here's a step-by-step solution in Pascal/Delphi:

Step 1: Read the input

We start by reading the input values. The first line contains the number of banknote denominations, N. The second line contains N distinct natural numbers representing the denominations of the banknotes. The third line contains the sum, S, that needs to be represented.

Step 2: Initialize variables

We initialize a variable, `count`, to keep track of the minimum number of banknotes used. We also initialize an array, `result`, to store the banknote denominations used to represent the sum.

Step 3: Sort the denominations in descending order

To ensure that we use the highest denominations first, we sort the denominations in descending order.

Step 4: Find the banknotes

We iterate through the sorted denominations and check if the current denomination can be used to represent the remaining sum. If it can, we subtract the denomination from the sum and add it to the `result` array. We also increment the `count` variable. We continue this process until the sum becomes zero.

Step 5: Output the result

If the sum becomes zero, we output the `result` array, which contains the banknote denominations used to represent the sum. If the sum does not become zero, it means that there is no solution, and we output "No solution".

Here's the Pascal/Delphi code that implements the above steps:

```pascal program BanknoteRepresentation;

var N, i, S, count: integer; denominations, result: array of integer;

begin // Step 1: Read the input readln(N); SetLength(denominations, N); for i := 0 to N - 1 do read(denominations[i]); readln(S);

// Step 2: Initialize variables count := 0; SetLength(result, N);

// Step 3: Sort the denominations in descending order for i := 0 to N - 2 do for j := i + 1 to N - 1 do if denominations[i] < denominations[j] then begin temp := denominations[i]; denominations[i] := denominations[j]; denominations[j] := temp; end;

// Step 4: Find the banknotes i := 0; while (S > 0) and (i < N) do begin if S >= denominations[i] then begin S := S - denominations[i]; result[count] := denominations[i]; count := count + 1; end else i := i + 1; end;

// Step 5: Output the result if S = 0 then begin for i := 0 to count - 1 do write(result[i], ' '); writeln; end else writeln('No solution'); end. ```

For the given input example (5 1 3 7 12 32 40), the output will be "32 7 1".

Please note that this solution assumes that the banknote denominations are provided in descending order. If they are not, you can modify the code to sort them before proceeding with the algorithm.

I hope this helps! Let me know if you have any further questions.

0 0

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос