{ }codelper
returning several valuessentinel loopP0405

Santa's candy bag and the stockings

Santa carries a bag of candy from house to house and fills the stockings hung in each house.
The bag starts with S candies.
The first line gives S, and from the second line on the houses are given one per line, in the order Santa visits them.
A house line holds two integers k and m separated by a single space.
k is the number of stockings in that house, and m is the most candies that one stocking of that house can take.
The line "0 0" marks the end of the list of houses.
"0 0" is not a house, and any lines after it are ignored.
At each house Santa does these three things in order.
1.
If the bag holds fewer than k candies, he first goes to the sleigh store and fills the bag so that it holds exactly S candies.
This counts as one refill.
If the bag holds k candies or more, he does not refill.
2.
He puts the same number of candies into each of the k stockings.
The number per stocking, e, is the largest integer such that e is at most m and e × k is at most the number of candies in the bag.
3.
He takes e × k candies out of the bag.
Print e on one line for each house visited.
Then, on the last line, print the number of candies left in the bag after all houses and the number of refills, separated by a single space.
If "0 0" comes right on the second line, no house is visited, so print just one line: S and 0 separated by a single space.
Try writing a function that does steps 2 and 3 for one house and returns two values together: e and the number of candies left (grading looks only at the output).

Input
The first line is an integer S from 1 to 1,000,000,000; then 0 to 10,000 house lines (k from 1 to S, m from 1 to 1,000,000,000); then one line "0 0" (always present); then 0 to 100 lines to ignore (in the same form as house lines, or "0 0")
Output
One line with e per house, then one last line with the candies left and the number of refills
Example 1 · stdin
10
3 2
2 5
4 1
3 10
0 0
5 5
stdout
2
2
1
2
0 1
Example 2 · stdin
7
2 2
4 1
3 5
0 0
stdout
2
1
1
0 1
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

After one house you need to know two things: e, the number put into each stocking, and how many candies are left in the bag.
Languages differ in how a function returns two values together.
Python returns the tuple return each, bag - each * k and receives it with each, bag = fill(bag, k, m).
JavaScript returns the array return [each, left] and unpacks it with const [each, left] = fill(bag, k, m); TypeScript writes the return type as the tuple [number, number].
C# returns the tuple (int each, int left) and can unpack it straight into the existing variable bag with (each, bag) = Fill(bag, k, m).
C++ receives a std::pair<int, int> with auto [each, left] = fill(bag, k, m); (C++17).
Java returns only one value, so it bundles them in record Fill(int each, int left) {} and reads f.left().
C also returns only one value, so e goes through return and the number left is written through a pointer int *left (fill(bag, k, m, &bag)).
Craykon returns the list return [each, bag - each * k]; and reads it as r[0], r[1].
The end marker is the line "0 0".
Put reading and asking in one condition as in C while (scanf("%d %d", &k, &m) == 2 && !(k == 0 && m == 0)) and C++ while (std::cin >> k >> m && !(k == 0 && m == 0)), or, as in Python, Java and C#, read inside while True/while (true) and leave with break.
JS/TS loop over the list of lines and break; Craykon reads once with Console.ReadNumbers() before the loop and reads again at the very end of the while block.
Trap one: writing return each, bag - each * k; in JavaScript as in Python makes it the comma operator, so only the value after the comma (the number left) comes back.
Unpacking that with const [each, left] = ... cannot unpack a number, and example 1 stops with a TypeError.
TypeScript's type check rejects the line with TS2695 (left side of the comma operator is unused).
In C, the same line in a function returning int compiles as the comma operator (the judge's gcc 11 only warns) and returns only the number left.
In C++, in a function returning std::pair<int, int>, it is a compile error because an int cannot become a pair, and in Java and C# it is a compile error too.
Trap two: making the parameter bag smaller inside a C function leaves main's bag unchanged, because C passes a copy of the value.
Using only r[0] in Craykon and dropping r[1] does the same.
The bag never shrinks, and example 1 becomes 2 5 1 3 / 10 0.
Trap three: receiving in the opposite order to the return, as in bag, each = fill(...), only swaps the names; the values still go by position, and example 1 becomes 4 0 6 1 / 3 2.
Trap four: refill only when the bag holds 'fewer' than k candies.
Writing bag <= k also refills at the third house of example 2 (3 candies left, 3 stockings) and prints 2 1 2 / 1 2.
Trap five: a refill must make the bag hold exactly S.
Adding S with bag += S turns example 2 into 2 1 2 / 0 1.
Trap six: reading to the end of input and only skipping "0 0" treats the lines after the end marker as houses too; example 1 gets one more house "5 5" and prints 2 2 1 2 2 / 0 2.
e × k never exceeds the candies in the bag, so nothing passes one billion and a 32-bit int is enough in every language.

Pythonmain.py · 21 lines
def fill(bag, k, m):    """양말 k개에 똑같이 넣고 (양말 하나에 넣은 개수, 남은 주머니 사탕 수)를 돌려준다."""    each = min(m, bag // k)    return each, bag - each * k  s = int(input())bag = srefills = 0out = []while True:    k, m = map(int, input().split())    if k == 0 and m == 0:  # 끝 표시: 그 뒤의 줄은 읽지 않는다        break    if bag < k:  # 한 개씩도 못 넣으면 S개가 되도록 채운다        bag = s        refills += 1    each, bag = fill(bag, k, m)    out.append(str(each))out.append(f"{bag} {refills}")print("\n".join(out))
JavaScriptmain.js · 26 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n"); // 양말 k개에 똑같이 넣고 [양말 하나에 넣은 개수, 남은 주머니 사탕 수]를 돌려준다function fill(bag, k, m) {  const each = Math.min(m, Math.floor(bag / k));  return [each, bag - each * k];} const s = Number(lines[0]);let bag = s;let refills = 0;const out = [];for (let i = 1; i < lines.length; i++) {  const [k, m] = lines[i].trim().split(" ").map(Number);  if (k === 0 && m === 0) break; // 끝 표시: 그 뒤의 줄은 보지 않는다  if (bag < k) {    // 한 개씩도 못 넣으면 S개가 되도록 채운다    bag = s;    refills++;  }  const [each, left] = fill(bag, k, m);  bag = left;  out.push(each);}out.push(`${bag} ${refills}`);console.log(out.join("\n"));
TypeScriptmain.ts · 27 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n"); // 양말 k개에 똑같이 넣고 [양말 하나에 넣은 개수, 남은 주머니 사탕 수]를 돌려준다function fill(bag: number, k: number, m: number): [number, number] {  const each = Math.min(m, Math.floor(bag / k));  return [each, bag - each * k];} const s = Number(lines[0]);let bag = s;let refills = 0;const out: string[] = [];for (let i = 1; i < lines.length; i++) {  const [k, m] = lines[i].trim().split(" ").map(Number);  if (k === 0 && m === 0) break; // 끝 표시: 그 뒤의 줄은 보지 않는다  if (bag < k) {    // 한 개씩도 못 넣으면 S개가 되도록 채운다    bag = s;    refills++;  }  const [each, left] = fill(bag, k, m);  bag = left;  out.push(String(each));}out.push(`${bag} ${refills}`);console.log(out.join("\n"));
JavaMain.java · 35 lines
import java.io.*;import java.util.StringTokenizer; public class Main {    // Java 메서드는 값 하나만 돌려주니 record로 묶는다    record Fill(int each, int left) {}     // 양말 k개에 똑같이 넣고 (양말 하나에 넣은 개수, 남은 주머니 사탕 수)를 돌려준다    static Fill fill(int bag, int k, int m) {        int each = Math.min(m, bag / k);        return new Fill(each, bag - each * k);    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int s = Integer.parseInt(in.readLine().trim());        int bag = s, refills = 0;        StringBuilder out = new StringBuilder();        while (true) {            StringTokenizer st = new StringTokenizer(in.readLine());            int k = Integer.parseInt(st.nextToken());            int m = Integer.parseInt(st.nextToken());            if (k == 0 && m == 0) break; // 끝 표시: 그 뒤의 줄은 읽지 않는다            if (bag < k) { // 한 개씩도 못 넣으면 S개가 되도록 채운다                bag = s;                refills++;            }            Fill f = fill(bag, k, m);            bag = f.left();            out.append(f.each()).append('\n');        }        out.append(bag).append(' ').append(refills).append('\n');        System.out.print(out);    }}
C#Main.cs · 36 lines
using System;using System.Text; class Program{    // 양말 k개에 똑같이 넣고 (양말 하나에 넣은 개수, 남은 주머니 사탕 수)를 튜플로 돌려준다    static (int each, int left) Fill(int bag, int k, int m)    {        int each = Math.Min(m, bag / k);        return (each, bag - each * k);    }     static void Main()    {        int s = int.Parse(Console.ReadLine().Trim());        int bag = s, refills = 0;        var sb = new StringBuilder();        while (true)        {            string[] parts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);            int k = int.Parse(parts[0]);            int m = int.Parse(parts[1]);            if (k == 0 && m == 0) break; // 끝 표시: 그 뒤의 줄은 읽지 않는다            if (bag < k) // 한 개씩도 못 넣으면 S개가 되도록 채운다            {                bag = s;                refills++;            }            int each;            (each, bag) = Fill(bag, k, m); // 이미 있는 변수 bag에 바로 풀어 넣는다            sb.Append(each).Append('\n');        }        sb.Append(bag).Append(' ').Append(refills).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 27 lines
#include <algorithm>#include <iostream>#include <utility> // 양말 k개에 똑같이 넣고 (양말 하나에 넣은 개수, 남은 주머니 사탕 수)를 돌려준다std::pair<int, int> fill(int bag, int k, int m) {    int each = std::min(m, bag / k);    return {each, bag - each * k};} int main() {    std::ios::sync_with_stdio(false);    int s, k, m;    std::cin >> s;    int bag = s, refills = 0;    // 끝 표시 0 0이 나오면 멈춘다: 그 뒤의 줄은 읽지 않는다    while (std::cin >> k >> m && !(k == 0 && m == 0)) {        if (bag < k) { // 한 개씩도 못 넣으면 S개가 되도록 채운다            bag = s;            refills++;        }        auto [each, left] = fill(bag, k, m);        bag = left;        std::cout << each << '\n';    }    std::cout << bag << ' ' << refills << '\n';}
Cmain.c · 27 lines
#include <stdio.h> /* 양말 k개에 똑같이 넣고, 양말 하나에 넣은 개수를 돌려준다.   C 함수는 값 하나만 돌려주니 남은 주머니 사탕 수는 포인터 *left에 써 준다 */static int fill(int bag, int k, int m, int *left) {    int each = bag / k;    if (each > m) each = m;    *left = bag - each * k;    return each;} int main(void) {    int s, k, m;    if (scanf("%d", &s) != 1) return 0;    int bag = s, refills = 0;    /* 끝 표시 0 0이 나오면 멈춘다: 그 뒤의 줄은 읽지 않는다 */    while (scanf("%d %d", &k, &m) == 2 && !(k == 0 && m == 0)) {        if (bag < k) { /* 한 개씩도 못 넣으면 S개가 되도록 채운다 */            bag = s;            refills++;        }        int each = fill(bag, k, m, &bag);        printf("%d\n", each);    }    printf("%d %d\n", bag, refills);    return 0;}
Craykonmain.cray · 27 lines
// 양말 k개에 똑같이 넣고 [양말 하나에 넣은 개수, 남은 주머니 사탕 수]를 목록으로 돌려준다양말채우기(bag, k, m){    each = Mathf.Min(m, Mathf.Quot(bag, k));    return [each, bag - each * k];} s = Console.ReadLine().ToNumber();bag = s;refills = 0;집 = Console.ReadNumbers();// 끝 표시 0 0이 나오면 멈춘다: 그 뒤의 줄은 읽지 않는다while (!(집[0] == 0 && 집[1] == 0)){    k = 집[0];    m = 집[1];    if (bag < k)    {        bag = s;        refills++;    }    r = 양말채우기(bag, k, m);    bag = r[1];    Console.WriteLine(r[0]);    집 = Console.ReadNumbers();}Console.WriteLine(bag + " " + refills);