Skip to content

About

challenging C programming problems for exam preparation

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

C Programming — 24 Challenging Real-World Practice Problems

A challenging, application-focused C practice set based on the supplied Lecture 1–7 syllabus: input/output, arithmetic, selection, switch, while/for/do-while, nested loops, break/continue, 1D arrays, and 2D arrays.

These are original practice problems, not official exam questions. Scenarios use fictional rules where applicable. No solution code is included, so you can attempt each problem independently.

How to use this set

  • Write a separate C program for each problem.
  • Use standard input and output. Do not print prompts or extra labels.
  • Whitespace separates input tokens unless stated otherwise. Print integer lists with one space between values.
  • Inputs satisfy the stated constraints except for cases that a problem explicitly asks you to validate.
  • Use 1-based positions in output when specified; C array indices are still 0-based.
  • Use double for real calculations and long long when integer totals may overflow int. Print decimal results with printf("%.2f", value).
  • All problems can be solved with the listed syllabus topics. Recursion, structs, dynamic allocation, and advanced data structures are unnecessary.
  • Each problem contains a task, input/output contract, constraints, at least two sample cases, and additional edge cases to test.
  • Suggested time limits are practice targets, not official exam limits. Trace a small case by hand, implement it, then check the boundary cases.

Study plan before Monday

  • First session: Problems 01–08 — arithmetic, decisions, and simulation.
  • Second session: Problems 09–18 — nested loops and 1D arrays.
  • Third session: Problems 19–24 — 2D arrays and integrated problems.
  • If time is short, prioritize 02, 05, 07, 09, 10, 13, 16, 19, 22, and 24.
  • Mock exam A (150 minutes): 02 (20 points), 07 (25), 14 (25), 19 (30).
  • Mock exam B (150 minutes): 05 (20 points), 10 (20), 18 (25), 24 (35).
  • Suggested marking per problem: 60% correct algorithm, 25% boundary/tie cases, 10% exact I/O, 5% readable code.

Coverage

  • 01–06: numerical decisions and basic search.
  • 07–12: loop simulation, counting, and patterns.
  • 13–18: 1D arrays and persistent state.
  • 19–24: 2D arrays, updates, and matrix applications.

Sample outputs were checked against reference calculations for all 57 sample cases.

01. Mixed-Unit Temperature Controller

Topics: Variables • double • if/else

Difficulty: Hard | Suggested time: 25 minutes

Task

A food container receives one temperature in C, F, or K. Convert it to Celsius: F uses (x-32)*5.0/9.0; K uses x-273.15. Print INVALID if the unit is unsupported or the input is below absolute zero (C: -273.15, F: -459.67, K: 0). Otherwise classify the unrounded Celsius value: below 0 = FREEZE; 0 through 4 = SAFE; above 4 through 10 = WARN; above 10 = DANGER. To accommodate conversion error, treat values within 1e-9 of a classification boundary as equal to that boundary. Apply the absolute-zero check to the original input value.

Input and constraints

One character unit and one real number x; -10000 ≤ x ≤ 10000. Valid unit letters are uppercase.

Output

Line 1: Celsius with exactly 2 decimal places. Line 2: status. For invalid input, print only INVALID.

Sample 1

Input:

F 39.2

Output:

4.00
SAFE

Sample 2

Input:

K -1

Output:

INVALID

Sample 3

Input:

C 10.01

Output:

10.01
DANGER

Additional cases to test

Test C temperatures 0, 4, and 10; K 0; and unit X. Use floating-point division and handle whitespace when reading a character.

02. Average-Speed Camera Across Midnight

Topics: Unit conversion • conditions • integers

Difficulty: Hard | Suggested time: 30 minutes

Task

Two cameras are d meters apart. Read entry and exit times as hours, minutes, and seconds. If the exit clock time is earlier, it is on the following day. Equal times are INVALID, not a 24-hour trip. Calculate the average speed in km/h. The fine is 0 if speed is at most L; 500 if it is above L but at most L+20; otherwise 1000. Classify using the unrounded speed.

Input and constraints

Line 1: d L. Lines 2 and 3: entry and exit times h m s. 1 ≤ d ≤ 1000000; 1 ≤ L ≤ 200; h=0..23; m,s=0..59.

Output

Line 1: elapsed seconds. Line 2: speed with 2 decimal places. Line 3: fine. For equal times, print only INVALID.

Sample 1

Input:

1500 60
23 59 30
0 0 30

Output:

60
90.00
1000

Sample 2

Input:

1000 60
12 0 0
12 1 0

Output:

60
60.00
0

Additional cases to test

Test speed exactly L+20 and equal timestamps. Convert each timestamp to seconds first.

03. Tiered Water Bill with a Conditional Discount

Topics: Multiple conditions • arithmetic

Difficulty: Hard | Suggested time: 30 minutes

Task

Use this fictional pricing scheme: the first 10 units cost 8 baht each, the next 20 cost 12 each, and units above 30 cost 15 each. Add a fixed service fee of 25 baht. Members (m=1) using at most 20 units receive a 10% discount on water charges only. Apply 7% VAT to the discounted water charges plus service fee. Do not round intermediate results.

Input and constraints

Two integers u m; 0 ≤ u ≤ 10000; m is 0 or 1.

Output

The final bill with exactly 2 decimal places.

Sample 1

Input:

20 1

Output:

219.35

Sample 2

Input:

31 0

Output:

385.20

Sample 3

Input:

0 1

Output:

26.75

Additional cases to test

Test u=10,20,21,30. Apply each rate only to the units in its tier; the service fee is not discounted.

04. Bus Fare with a Daily Spending Cap

Topics: switch • if/else • minimum

Difficulty: Hard | Suggested time: 25 minutes

Task

The regular fare is 12 + 3*max(0,z-2) baht for z zones. Passenger type 1 pays the full fare; type 2 is a student and pays half rounded UP to a whole baht; type 3 is a senior and pays zero. The actual charge must not increase the amount already paid today above 60 baht. Use switch to select the passenger type. Any other type is INVALID.

Input and constraints

Three integers type z paid; 1 ≤ z ≤ 20; 0 ≤ paid ≤ 60; type=0..9.

Output

Print the actual charge and new daily total on one line, or INVALID.

Sample 1

Input:

2 3 50

Output:

8 58

Sample 2

Input:

1 8 55

Output:

5 60

Sample 3

Input:

4 2 0

Output:

INVALID

Additional cases to test

Test paid=60, a senior passenger, and an odd regular fare for a student.

05. Limited-Banknote Change Machine

Topics: Nested loops • optimization • tie-breaking

Difficulty: Hard | Suggested time: 35 minutes

Task

A machine has limited supplies of 100-, 50-, and 20-baht notes. Make exactly amount baht using the fewest notes. If multiple solutions use the same number, prefer more 100-baht notes, then more 50-baht notes. Taking the largest available note first is not guaranteed to work.

Input and constraints

amount n100 n50 n20; 0 ≤ amount ≤ 10000; each note count is 0..30.

Output

Print the counts of 100-, 50-, and 20-baht notes used, followed by their total count. If impossible, print IMPOSSIBLE.

Sample 1

Input:

60 0 1 3

Output:

0 0 3 3

Sample 2

Input:

180 1 2 4

Output:

1 0 4 5

Sample 3

Input:

0 0 0 0

Output:

0 0 0 0

Additional cases to test

Test amount=0, insufficient notes, and an amount not divisible by 10. Compare all feasible candidates.

06. Expanding Rows in an Auditorium

Topics: for/while • cumulative sums

Difficulty: Hard | Suggested time: 25 minutes

Task

The first row has a seats. Each subsequent row has d more seats than the previous row. Build the fewest complete rows needed to seat n people. People fill seats from the first row onward. Report the number of rows, total seats, and empty seats in the last row. For n=0, use zero rows and zero seats.

Input and constraints

Three integers n a d; 0 ≤ n ≤ 1000000; 1 ≤ a ≤ 1000; 0 ≤ d ≤ 100.

Output

Print rows total empty on one line.

Sample 1

Input:

31 5 2

Output:

4 32 1

Sample 2

Input:

20 5 0

Output:

4 20 0

Sample 3

Input:

0 5 2

Output:

0 0 0

Additional cases to test

Test an exact fit, d=0, and one person.

07. A Bus Visiting Multiple Stops

Topics: Loops • state tracking • validation

Difficulty: Hard | Suggested time: 35 minutes

Task

A bus starts empty and holds C passengers. At each of N stops, off passengers leave first, then on people attempt to board. Admit only as many as fit. Rejected people do not reappear at later stops. If off exceeds the number on board before that stop, stop the simulation and report INVALID with the 1-based stop number. Otherwise calculate the final load, total rejected passengers, and highest load after boarding at any stop.

Input and constraints

C N, followed by N lines containing off on. 1 ≤ C ≤ 1000; 1 ≤ N ≤ 1000; 0 ≤ off,on ≤ 1000.

Output

Print final rejected peak, or INVALID stop.

Sample 1

Input:

5 3
0 4
2 5
4 1

Output:

2 2 5

Sample 2

Input:

5 2
0 2
3 1

Output:

INVALID 2

Additional cases to test

Test a full bus, everyone leaving, and nobody boarding. Validate off before changing the load.

08. Monthly Savings with Rounded Bonuses

Topics: do-while • integer rounding

Difficulty: Hard | Suggested time: 30 minutes

Task

Start with S baht and a target T. If the initial balance already reaches T, the answer is zero months. Otherwise, each month deposit D first, then add a bonus of floor(balance_after_deposit*p/100) baht. Bonuses remain in the account. Stop upon reaching T or after M months. Use do-while for the simulation.

Input and constraints

S T D p M; 0 ≤ S ≤ 1000000; 1 ≤ T ≤ 1000000; 0 ≤ D ≤ 10000; 0 ≤ p ≤ 10; 1 ≤ M ≤ 120.

Output

If successful, print months balance. Otherwise print NOT_REACHED balance.

Sample 1

Input:

100 150 20 10 12

Output:

2 167

Sample 2

Input:

0 10 0 10 3

Output:

NOT_REACHED 0

Sample 3

Input:

50 50 10 1 12

Output:

0 50

Additional cases to test

Round the bonus down each month. Test an initially sufficient balance and a balance that never grows.

09. Temperature Stream with Broken Readings

Topics: while • break • continue

Difficulty: Hard | Suggested time: 30 minutes

Task

Read integer temperatures until sentinel 999. Values outside -50..60 are invalid: count and skip them using continue. Invalid readings also break any consecutive hot streak. Valid readings of at least 35 are hot. Find the counts of valid and invalid readings, the average of valid readings, and the longest hot streak. Do not count the sentinel.

Input and constraints

Whitespace-separated integers, ending with 999. At most 10000 readings precede it. Readings are -1000..1000; 999 is reserved for termination.

Output

Line 1: good bad. Line 2: average with 2 decimal places, or NO_DATA. Line 3: longestHot.

Sample 1

Input:

30 35 40 100 36 37 999

Output:

5 1
35.60
2

Sample 2

Input:

100 -100 999

Output:

0 2
NO_DATA
0

Additional cases to test

Test an immediate sentinel, all-hot readings, and an invalid reading interrupting a hot streak.

10. Three-Dice Outcome Counter

Topics: Nested loops • modulo • counting

Difficulty: Hard | Suggested time: 35 minutes

Task

Three distinguishable dice each have faces 1..S. Count ordered outcomes (a,b,c) whose sum is in L..U inclusive, with exactly E even-valued dice, and with at least two dice showing the same value. Three equal dice also qualify. Outcomes (1,1,2), (1,2,1), and (2,1,1) are distinct.

Input and constraints

S L U E; 2 ≤ S ≤ 20; 3 ≤ L ≤ U ≤ 3*S; 0 ≤ E ≤ 3.

Output

Print the number of qualifying ordered outcomes.

Sample 1

Input:

2 3 6 1

Output:

3

Sample 2

Input:

2 3 6 2

Output:

3

Sample 3

Input:

6 3 3 0

Output:

1

Additional cases to test

Do not restrict enumeration to a≤b≤c. Test no qualifying outcomes and three equal dice.

11. Lucky Four-Digit Bus Tickets

Topics: Loops • integer division • modulo

Difficulty: Hard | Suggested time: 30 minutes

Task

Examine all ticket numbers from A through B inclusive. Always interpret a number as four digits, so 27 is 0027. A lucky ticket has equal sums of its first two and last two digits, and no identical adjacent digits. For example, 0110 fails because its middle digits match. Find the lucky-ticket count and smallest lucky ticket.

Input and constraints

A B; 0 ≤ A ≤ B ≤ 9999.

Output

Print count smallest, padding smallest to 4 digits. If none exist, print 0 NONE.

Sample 1

Input:

1000 1020

Output:

1 1010

Sample 2

Input:

0 9

Output:

0 NONE

Additional cases to test

Leading zeros are real digits for both rules. Check all three adjacent pairs.

12. Snake-Numbered Bus Seating Plan

Topics: Nested loops • output patterns

Difficulty: Hard | Suggested time: 30 minutes

Task

A bus has R rows with an even number C of seats per row. Number row 1 left to right from 1 to C, row 2 right to left, and alternate thereafter. Display every row from left to right. Insert an aisle token | between the left and right halves. Replace every seat number divisible by K with XX.

Input and constraints

R C K; 1 ≤ R ≤ 20; 2 ≤ C ≤ 10 with C even; 1 ≤ K ≤ 200.

Output

Print R lines. Separate all tokens, including |, with one space. Do not pad numbers with zeros or print trailing spaces.

Sample 1

Input:

2 4 3

Output:

1 2 | XX 4
8 7 | XX 5

Sample 2

Input:

1 2 1

Output:

XX | XX

Additional cases to test

The aisle is not a seat. Even-numbered rows display their seat numbers in reverse order.

13. Fastest Consecutive Road Segments

Topics: 1D Array • windows • tie-breaking

Difficulty: Hard | Suggested time: 35 minutes

Task

A vehicle travels N road segments, each D meters long. Given each segment's travel time, select K consecutive segments with the highest overall average speed. Break ties by choosing the earliest starting segment. Overall speed is total distance divided by total time, not the average of individual segment speeds.

Input and constraints

N K D, then N integer times t. 1 ≤ K ≤ N ≤ 1000; 1 ≤ D ≤ 100000; 1 ≤ t ≤ 10000 seconds.

Output

Line 1: start end, using 1-based indices. Line 2: overall speed in km/h with 2 decimal places.

Sample 1

Input:

5 2 1000
60 30 30 90 30

Output:

2 3
120.00

Sample 2

Input:

3 2 500
30 30 30

Output:

1 2
60.00

Additional cases to test

Test K=1, K=N, and equal total times. Use floating-point arithmetic for speed.

14. Longest Affordable Spending Streak

Topics: 1D Array • nested loops

Difficulty: Very hard | Suggested time: 40 minutes

Task

Given nonnegative expenses for N days, find the longest nonempty interval of consecutive days whose total expense is at most B. If several intervals have equal length, choose the earliest start. If no day is affordable, print NONE. An O(N²) solution is acceptable.

Input and constraints

N B, then N expenses. 1 ≤ N ≤ 500; 0 ≤ B ≤ 1000000; 0 ≤ expense ≤ 10000.

Output

Print start end sum using 1-based days, or NONE.

Sample 1

Input:

6 10
4 2 3 5 1 1

Output:

3 6 10

Sample 2

Input:

3 0
1 0 0

Output:

2 3 0

Sample 3

Input:

2 1
2 3

Output:

NONE

Additional cases to test

Zero-expense days count toward interval length. Maximize length, not spending.

15. Dice Frequency and Repeated Runs

Topics: 1D frequency array • ranking

Difficulty: Hard | Suggested time: 30 minutes

Task

Given N dice rolls, report all six face frequencies, the most frequent face, and the longest consecutive run of identical faces. If multiple faces share the highest frequency, select the smallest face.

Input and constraints

N, then N face values. 1 ≤ N ≤ 10000; 1 ≤ face ≤ 6.

Output

Line 1: frequencies of faces 1 through 6. Line 2: mode count. Line 3: longestRun.

Sample 1

Input:

8
2 2 3 3 3 2 6 6

Output:

0 3 3 0 0 2
2 3
3

Sample 2

Input:

1
6

Output:

0 0 0 0 0 1
6 1
1

Additional cases to test

The mode need not produce the longest consecutive run. Print zero for faces that never appear.

16. Vending Machine Inventory

Topics: 1D Array • switch • transactions

Difficulty: Very hard | Suggested time: 40 minutes

Task

There are N products numbered 1..N, each with a price and stock. Process Q commands using switch. Command 1 id qty money buys a product: invalid id or nonpositive qty → INVALID; otherwise insufficient stock → SOLD_OUT; otherwise insufficient money → NEED_MORE; otherwise print OK change and reduce stock. Check failures in that exact order. Command 2 id qty restocks: invalid id or nonpositive qty → INVALID; otherwise increase stock and print RESTOCKED. Failed commands never change stock.

Input and constraints

N Q; N lines of price stock; then Q commands in the formats above. 1 ≤ N ≤ 20; 1 ≤ Q ≤ 100; price=1..1000; stock=0..1000; qty=-10..100; money=0..100000; id=0..N+1. Only op 1 or 2 occurs.

Output

Print one result per command. On the final line, print all final stock counts in product-ID order.

Sample 1

Input:

2 4
10 2
15 0
1 1 2 25
1 1 1 100
2 2 3
1 2 2 20

Output:

OK 5
SOLD_OUT
RESTOCKED
NEED_MORE
0 3

Sample 2

Input:

1 2
10 5
1 0 1 20
2 1 0

Output:

INVALID
INVALID
5

Additional cases to test

If both stock and money are insufficient, print SOLD_OUT. Validate the ID before indexing an array.

17. Circular Staff Roster

Topics: 1D Array • modulo

Difficulty: Hard | Suggested time: 30 minutes

Task

A roster contains N employee IDs. Apply Q shifts in order. A positive k rotates the roster right by k positions; a negative k rotates it left. Each command acts on the previous result. Values of |k| can exceed N. Print the final roster.

Input and constraints

N Q; N employee IDs; Q shift values k. 1 ≤ N ≤ 100; 0 ≤ Q ≤ 100; IDs=1..9999; -1000000 ≤ k ≤ 1000000.

Output

Print the final employee IDs in order on one line.

Sample 1

Input:

5 2
10 20 30 40 50
2 -1

Output:

50 10 20 30 40

Sample 2

Input:

3 1
1 2 3
-4

Output:

2 3 1

Additional cases to test

Test Q=0, N=1, k=0, and negative shifts. Account for C's negative remainder behavior.

18. Trim Extreme Revenue Days

Topics: 1D Array • min/max • averages

Difficulty: Very hard | Suggested time: 40 minutes

Task

Given revenue for N days, remove exactly one minimum-revenue day, choosing the earliest on a tie. Then remove exactly one maximum-revenue day among the remaining days, choosing the latest on a tie. Calculate the remaining average and find the remaining day whose revenue is closest to that average. Break this final tie by earliest day. Do not round the average before comparisons.

Input and constraints

N, then N revenue values. 3 ≤ N ≤ 1000; 0 ≤ revenue ≤ 1000000.

Output

Line 1: removedMinDay removedMaxDay. Line 2: remaining average with 2 decimal places. Line 3: closestDay. All day numbers are 1-based.

Sample 1

Input:

5
10 20 20 30 100

Output:

1 5
23.33
2

Sample 2

Input:

4
7 7 7 7

Output:

1 4
7.00
2

Additional cases to test

Test all-equal values. The two removed days must differ. Exact comparison can use |revenue*(N-2)-sum| with long long.

19. Consecutive Cinema Seat Reservations

Topics: 2D Array • search • updates

Difficulty: Very hard | Suggested time: 40 minutes

Task

A cinema has an R×C seating grid: 0 means free, 1 means occupied. Process Q groups sequentially; each requests k consecutive seats in one row. Choose the smallest row number first, then the smallest starting column. Mark successfully reserved seats as 1 immediately. If no block fits, print REJECT without changing the grid.

Input and constraints

R C Q; R grid rows; Q group sizes k. 1 ≤ R,C ≤ 30; 1 ≤ Q ≤ 100; 1 ≤ k ≤ C+1.

Output

For each group print row start end, or REJECT. Then print FINAL and the final grid. All positions are 1-based.

Sample 1

Input:

2 5 3
0 0 1 0 0
0 0 0 0 0
3 2 2

Output:

2 1 3
1 1 2
1 4 5
FINAL
1 1 1 1 1
1 1 1 0 0

Sample 2

Input:

1 2 1
0 1
2

Output:

REJECT
FINAL
0 1

Additional cases to test

Total free seats may be sufficient without any consecutive block. Test k>C and competing requests.

20. Hotspots on a Temperature Map

Topics: 2D Array • neighbors • boundaries

Difficulty: Hard | Suggested time: 35 minutes

Task

A hotspot is a cell strictly hotter than every existing orthogonal neighbor: above, below, left, and right. Ignore diagonals and nonexistent neighbors. A 1×1 grid has one hotspot by definition. List all hotspots in row-major order.

Input and constraints

R C, then an integer grid. 1 ≤ R,C ≤ 50; temperatures=-100..100.

Output

First print the hotspot count. Then print row col temperature for each hotspot, using 1-based positions. If none exist, print only 0.

Sample 1

Input:

3 3
1 2 1
2 9 2
1 2 8

Output:

2
2 2 9
3 3 8

Sample 2

Input:

1 2
5 5

Output:

0

Sample 3

Input:

1 1
-4

Output:

1
1 1 -4

Additional cases to test

Test negative temperatures, corners, and equal adjacent values. Equality does not qualify.

21. Revenue Across Bus Routes and Days

Topics: 2D Array • matrix/vector calculations • sums

Difficulty: Hard | Suggested time: 35 minutes

Task

Matrix A has R bus routes and D days. A[r][d] is the number of passengers on route r on day d. Vector fare gives the per-passenger fare for each route. Calculate revenue for each day, total revenue for each route, and the highest-earning route. Break ties by smallest route number.

Input and constraints

R D; R rows of A with D values each; R fare values. 1 ≤ R,D ≤ 30; passengers=0..1000000; fare=1..1000.

Output

Line 1: D daily revenues. Line 2: R route revenues. Line 3: bestRoute total, with routes numbered from 1. Use 64-bit integers.

Sample 1

Input:

2 3
2 0 3
1 4 0
10 20

Output:

40 80 30
50 100
2 100

Sample 2

Input:

2 1
0
0
10 20

Output:

0
0 0
1 0

Additional cases to test

The fare vector has one entry per route, not per day. Totals can exceed a 32-bit int.

22. Warehouse Columns: Insert, Delete, Swap

Topics: 2D Array • shifting • commands

Difficulty: Very hard | Suggested time: 50 minutes

Task

A warehouse grid has R rows and C columns. Process commands sequentially: I p followed by R values inserts a column before position p; p=C+1 appends it. D p deletes column p. S a b swaps columns a and b. Positions refer to the current grid. Commands are guaranteed valid, and the grid always has 1..10 columns after each command. Its number of rows never changes.

Input and constraints

R C Q; R grid rows; Q command lines. 1 ≤ R,C ≤ 10; 0 ≤ Q ≤ 30; inventory values=0..1000. Column positions are 1-based.

Output

Print R finalC, then the final grid.

Sample 1

Input:

2 3 3
1 2 3
4 5 6
I 2 9 8
D 4
S 1 3

Output:

2 3
2 9 1
5 8 4

Sample 2

Input:

1 1 1
7
I 2 9

Output:

1 2
7 9

Additional cases to test

Test insertion at either end and swapping a column with itself. During insertion, avoid overwriting values that still need to move.

23. Solar Panels on a Blocked Roof

Topics: 2D Array • rectangular windows • tie-breaking

Difficulty: Very hard | Suggested time: 45 minutes

Task

An R×C roof map contains nonnegative energy values, or -1 for blocked cells. Place one H×W rectangle containing no blocked cell and maximizing total energy. You may not rotate the rectangle. Break ties by the smallest top-left row, then the smallest column.

Input and constraints

R C H W, then the grid. 1 ≤ H ≤ R ≤ 20; 1 ≤ W ≤ C ≤ 20; values are -1 or 0..1000.

Output

Print row col total for the chosen top-left corner using 1-based positions, or IMPOSSIBLE if no placement works.

Sample 1

Input:

3 4 2 2
1 2 -1 4
3 4 5 6
0 1 2 3

Output:

2 3 16

Sample 2

Input:

2 2 2 2
1 -1
2 3

Output:

IMPOSSIBLE

Additional cases to test

An all-zero rectangle is valid. One blocked cell invalidates the entire candidate. Test a rectangle as large as the roof.

24. Two-Leg Bus Connections

Topics: 2D Array • matrix multiplication

Difficulty: Very hard | Suggested time: 45 minutes

Task

A[i][k] counts travel options from origin i to transfer point k. B[k][j] counts travel options from transfer point k to destination j. Each first-leg option can pair with every second-leg option. Compute C[i][j] as the sum over k of A[i][k]*B[k][j]. These are counts of distinct two-leg travel choices, not bus capacities. Also report the origin–destination pair with the largest count. Break ties by smallest origin, then smallest destination.

Input and constraints

N K M; N rows of A with K values each; K rows of B with M values each. 1 ≤ N,K,M ≤ 20; values=0..10000.

Output

Print the N×M result matrix, then origin destination ways. Positions are 1-based. Use long long.

Sample 1

Input:

2 2 2
1 2
0 3
2 1
4 0

Output:

10 1
12 0
2 1 12

Sample 2

Input:

1 2 1
0 0
5
8

Output:

0
1 1 0

Additional cases to test

N, K, and M need not be equal. Reset each cell's accumulator. A result can exceed a 32-bit int.

About

challenging C programming problems for exam preparation

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors