We are given: N items, M shops. For each item i and each shop j, we have three successive discounts: d1, d2, d3 (percentages). The base price of each item is the same across all shops. So we only care about effective discount (or final price). Since base price same, we need to compute effective price after applying three successive discounts: Let base price = B (unknown, but same for all shops for that item). For discounts a%, b%, c%, the final price = B * (1 - a/100) * (1 - b/100) * (1 - c/100). Since B is constant for the item, the best price is the one with smallest product (1 - a/100)(1 - b/100)(1 - c/100). Equivalent to largest discount overall (i.e., smallest multiplicative factor). Since we only need compare across shops, we can compute the product factor = (100 - a)(100 - b)(100 - c) (since division by 100^3 constant). Actually the factor = (100 - a)/100 * (100 - b)/100 * (100 - c)/100 = ( (100-a)(100-b)(100-c) ) / 10^6. Since denominator is constant, we can compare numerator: (100-a)(100-b)(100-c). The best price (lowest final price) corresponds to smallest product numerator? Let's check: final price = B * product / 10^6. So lower final price means smaller product. So we want the shop that minimizes (100-a)(100-b)(100-c). If there is tie, choose lower shop index.
Note: Discounts can be 0 to 100. So 100 discount means factor = 0; product becomes 0, so final price = 0. If multiple shops have product = 0, choose lower index. If discount 100% appears, product becomes 0. That is best possible price (free). So we must handle.
Given constraints: N, M up to 1000. So total entries: N * M * 3 integers, up to 1e6 * 3 = 3e6? Actually N*M can be up to 1e6 (since both up to 1000, product 1e6). So input size up to 3e6 ints. We need fast I/O.
We need for each item i, among M shops, compute product = (100 - d1)(100 - d2)(100 - d3) (or maybe use double?). But product could be up to 100^3 = 1e6? Actually (100-0)^3 = 1e6. So fits in int (max 1e6). But careful: discounts could be 100? Then factor 0. So product fits in 32-bit integer. So we can compute integer product for comparison.
But note: Actually (100-d) values range 0..100. So product range 0..1,000,000. So int fine.
But wait: What if discounts are 100? Then factor 0 => product 0. So best price zero. So we need to handle zero product. But product = 0 is minimum possible.
We need for each item, output the shop index (1-based) that gives minimal product. In case of tie, smallest index.
Simple approach: For each item, iterate over M shops, read three ints, compute product, track min product and corresponding index (first encountered min). Output indices.
But input format: The description of N products: each product description consists of M lines with 3 integers each. So for each product i, there are M lines, each line containing three discounts for that product from shop 1 to M? Actually sample:
SAMPLE INPUT:
2
1 3
20 20 50
30 20 0
60 50 0
2 2
20 20 20
30 20 40
10 100 90
35 60 50
Interpretation: For test case 1: N=1, M=3. Then description of 1 product: M lines: each line has 3 integers. So we have 3 lines: "20 20 50" (shop1), "30 20 0" (shop2), "60 50 0" (shop3). So product1: shop1 discounts 20,20,50; shop2 discounts 30,20,0; shop3 discounts 60,50,0. Then output: 3. So indeed for each product we have M lines each with the three discounts for that shop.
Second test case: N=2, M=2. Then product1: first M=2 lines: "20 20 20" (shop1), "30 20 40" (shop2). Then product2: next M=2 lines: "10 100 90" (shop1), "35 60 50" (shop2). Output: "2 1". For product1, compute product: shop1: (808080?) Actually discounts: 20,20,20 => factors (80,80,80) product=512000? Wait (808080=512000). Shop2: discounts 30,20,40 => (70,80,60) product=708060=336000. So shop2 product is smaller => cheaper? 336000 < 512000, so shop2 is cheaper. So output 2. For product2: shop1: 10,100,90 => (90,0,10) product=0? Actually 100% discount makes factor 0 => product = 0. So final price = 0. shop2: 35,60,50 => (65,40,50) product=654050=130000. So shop1 product 0 is min => output 1. So output "2 1" matches.
Thus the algorithm is straightforward.
But constraints say "Large I/O files." So we need efficient reading and writing.
Implementation details:
- Use sys.stdin.buffer.read() to read all bytes, split, map to ints.
- Or use sys.stdin.buffer.readline in loops, but with up to 3e6 ints, Python might be fine with fast reading.
But careful: T up to? Not specified; but typical maybe up to 10? N*M up to 10^6 per test? With T maybe small. But total input size could be up to 3 million ints per test, which is okay. Use sys.stdin.buffer.read to parse all ints.
We'll parse all ints from input. Then process.
Steps:
- Read all ints from stdin: data = list(map(int, sys.stdin.buffer.read().split()))
- Use an iterator.
But need to handle T test cases.
Alternatively, use fast reading via sys.stdin.readline inside loops; but reading line by line and splitting 3 ints is fine; we have at most 1e6 lines per test (since N*M lines). That's okay. However, using readline in Python might be okay if we use .split() each line. But there might be many lines, but still acceptable. But to be safe, using sys.stdin.buffer.read is more efficient.
We'll implement:
import sys
def solve():
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
t = next(it)
out_lines = []
for _ in range(t):
n = next(it); m = next(it)
# For each item
item_best = []
for i in range(n):
best_prod = 10**9 # large, or maybe None, but product max 1e6
best_shop = 0
for shop in range(1, m+1):
a = next(it); b = next(it); c = next(it)
# compute product (100-a)(100-b)(100-c)
prod = (100 - a) * (100 - b) * (100 - c)
if prod < best_prod:
best_prod = prod
best_shop = shop
item_best.append(str(best_shop))
out_lines.append(' '.join(item_best))
sys.stdout.write('\n'.join(out_lines))
if name == 'main':
solve()
That's it.
But wait: The input might have line breaks after each line; but reading ints sequentially works fine.
Edge Cases:
- Discounts 100: 100-a = 0, product 0 => best.
- Discounts 0: product up to 1e6.
- If multiple shops have same product, the first encountered (lower index) will be kept because we only update when prod < best_prod (strictly less). So tie goes to lower index.
Potential pitfalls: product could be large? (100-0)^3 = 1,000,000. That's fine. But there is also chance of negative? Discounts are between 0 and 100 inclusive, so 100-a non-negative. So product non-negative.
Thus solution is simple.
But let's consider that maybe the problem description means discounts are applied in order: first discount a%, then on the new price b%, then c%. That's exactly the multiplicative model we used.
Thus answer.
But check: In sample test case 1: N=1 M=3. Shops:
1: 20 20 50 => (808050?) Actually 100-20=80, 100-20=80, 100-50=50 => product = 808050=320,000? Wait 8080=6400, 50 = 320,000.
2: 30 20 0 => 7080100=560,000? Actually 100-0=100 => product=7080100=560,000.
3: 60 50 0 => 4050100=200,000. So min product is 200,000 (shop3). So output 3. So correct.
Thus algorithm is correct.
Complexity: O(T * N * M) time, O(1) extra per test (except output). Memory for reading all ints might be high if total input large, but we can process incrementally by reading line by line. But with N,M <=1000, each test max lines = N*M <= 1e6. Each line has 3 ints. So total ints per test <= 3e6. At 4 bytes per int (in Python, more), list of ints may be heavy: Python ints are objects, each ~28 bytes, 3e6 ints would be ~84 MB, plus overhead, may be high but borderline. Better to avoid storing all ints at once if many test cases. But typical problem constraints might have total input size moderate; but to be safe, we can process with reading line by line. However, reading all at once and converting to ints might be memory heavy for 3e6 ints: each Python int ~28 bytes -> ~84 MB, plus list overhead, maybe ~100-200 MB. Could be okay if memory limit is 256 MB? But Python might exceed. So safer to read line by line.
But there is T test cases; total input across test cases could be larger. To be safe, use sys.stdin.buffer.readline for each line. We'll read T first.
Approach with line by line:
- Read first line integer T.
- Loop for each test case.
- For each test case, read N and M from next line (split).
- Then for each item i in range(N):
- For each shop j in range(M):
- read line, get three ints.
- compute product.
- After processing M shops for current item, we have best shop for that item. Append to list.
- After all items, output the list.
But careful: Input lines for each product are exactly M lines. So total lines for a test case: 1 for N M, then N*M lines. That's fine.
Implementation:
import sys
def solve():
data = sys.stdin.buffer
t_line = data.readline()
while t_line.strip() == b'': t_line = data.readline() # skip empty?
T = int(t_line)
out_lines = []
for _ in range(T):
# read N M line
line = data.readline()
while line.strip() == b'': line = data.readline()
parts = line.split()
while len(parts) < 2: # maybe need to read more? unlikely.
line = data.readline()
parts += line.split()
n = int(parts[0]); m = int(parts[1])
# We'll process n items
item_shops = []
for i in range(n):
best_prod = 10**9
best_shop = 0
for shop in range(1, m+1):
# read line
line = data.readline()
while line.strip() == b'': line = data.readline() # skip empty lines
a,b,c = map(int, line.split())
prod = (100 - a) * (100 - b) * (100 - c)
if prod < best_prod:
best_prod = prod
best_shop = shop
item_shops.append(str(best_shop))
out_lines.append(' '.join(item_shops))
sys.stdout.write('\n'.join(out_lines))
if name == 'main':
solve()
But note: There could be blank lines? Usually not, but we can handle.
Potential issue: The input might be huge and reading line by line might be okay but the inner loop reading M lines per item, total NM lines, each line we split into 3 ints. Splitting each line may be slower than reading all ints, but still feasible within time if coded efficiently. With N,M up to 1000, NM up to 1e6 lines, each line splitted and mapped to ints, that's okay for Python if optimized (like using map(int, line.split())). But 1e6 lines each with 3 ints is moderate, but might be near time limit if not careful. However, we can also use reading all ints and using iterator, which might be faster because we avoid per-line splits? Actually reading all ints via .read().split() and converting to ints via map is also fast; but memory might be high but maybe okay. Let's evaluate memory: Each int in Python is heavy, but we can avoid storing all ints by using a generator that yields ints from the bytes? For example, we can use sys.stdin.buffer.read().split() and then map to int, but that creates list of strings then list of ints. To reduce memory, we could use a custom fast integer parser that reads from buffer and yields ints one by one without storing all. But implementing that may be overkill.
Given constraints: N,M <= 1000, total ints per test <= 3e6. If T=1, 3e6 ints, list of ints ~ 3e6 * 28 = 84 MB, plus list overhead maybe 24 MB? Actually a list of 3e6 pointers is 24 MB (since each pointer 8 bytes), plus each int object ~28 bytes, total ~ 84+24=108 MB. That might be okay if memory limit is 256 MB or 512 MB. But if T=10, then 30e6 ints would be huge (1 GB) - not possible. However, problem likely limits total input size such that T is small, maybe T <= 10, but N,M each up to 1000, so worst-case total lines across tests: T * N * M up to maybe 10*1e6 = 10e6 lines? That's 30e6 ints. That could be too much memory if read all. But typical problems with "Large I/O files" often have a single test case, or moderate total input. However, to be safe, we should process test case by test case without storing all ints.
Alternative: Use sys.stdin.buffer.read to read entire input, but then process sequentially using a generator that yields ints without storing all as Python ints? Actually we can read all bytes, split into tokens (list of byte strings), which would still be memory heavy: each token is a bytes object, also overhead. So similar memory.
Better approach: use sys.stdin.buffer.readline per line and process.
Given that N,M <= 1000, N*M <= 1e6. For each line, we split and map to ints; splitting a short line with 3 numbers is fast. 1e6 lines may be okay in Python if well-optimized (should be within a couple seconds). But we also have T up to maybe 10? Could be up to 10 test cases => 10e6 lines => 30 million ints parsing, which could be borderline but still maybe okay if I/O fast (using sys.stdin.buffer). But typical contest time limit might be 1-2 seconds; 10e6 lines might be too slow in Python. But we might be able to use faster parsing: reading all data and using map on split bytes might be more efficient.
Let's consider typical constraints: The problem statement says "Large I/O files." But N and M both <= 1000, so max input size per test ~ 3e6 integers, which is about 3e6 * up to 4 chars each maybe ~12 MB of text. That's manageable. T might be up to 10? Then total 120 MB text. Reading line by line with Python may be okay.
Nevertheless, we can design a faster integer parser using sys.stdin.buffer.read and iterating over bytes to yield ints without constructing all tokens at once? That would be more complex.
Simplest: Use sys.stdin.buffer.read and map to ints, then iterate. But to avoid memory issues, we can process as we read? Actually we can read all, but we need to store all ints? Not if we use a generator. For example, we can do:
import sys
def ints():
for num in sys.stdin.buffer.read().split():
yield int(num)
Then we can use an iterator that yields ints from the entire input; but sys.stdin.buffer.read().split() still creates a list of byte strings (tokens) that consumes memory proportional to number of tokens. However, that may be okay given constraints.
Given the typical memory limit of 256MB, storing 3e6 tokens as bytes strings: each token maybe 1-3 bytes plus overhead. In CPython, bytes objects have overhead (33 bytes?). That would be huge. Better to avoid storing all tokens.
But we can use a scanning approach: read chunk by chunk, parse ints on the fly. However, this is more involved.
Perhaps the problem expects participants to use faster I/O like scanf in C, but for Python, reading line by line might be okay because 1e6 lines reading and splitting may be doable within time (maybe 1-2 seconds) if we use sys.stdin.buffer.readline and map(int, line.split()). I've seen Python handle 1e6 lines of few ints in about 1 second on fast machines. For 10e6 lines, might be 10 seconds, which could be too slow.
Let's examine sample constraints: N, M ≤ 1000 => N*M ≤ 1e6. So per test, 1e6 lines. Typically, there won't be 10 such tests; maybe T is small, like ≤ 5. So 5e6 lines. That may still be borderline but maybe acceptable if optimized.
Alternatively, we could read all data at once but process incrementally? Actually, we can read the entire input as bytes and then manually parse integers without creating a list of tokens? That is doable: define a function fast_ints that yields ints from a bytes object. But then we still hold the entire input bytes in memory (size ~ tens of MB), which is fine. For example, input size worst-case: 10 tests * (2 + 3e6) ints? Actually 3e6 ints per test, each int up to 3 digits plus spaces, average say 4 chars, total 12 MB per test, times 10 = 120 MB. That's a lot but still less than memory limit? 120 MB of raw bytes plus some overhead. Python bytes object of that size is okay? 120 MB might be high but possibly within memory limit (256 MB). However, Python might use more memory when we process. But if we parse on the fly we don't need to keep the bytes after parsing? Actually we read whole bytes into a single bytes object, which uses 120 MB, then we parse and yield ints. That uses additional memory for the generator? But the bytes object remains. But after parsing we could discard? But we need to process all test cases, so we might keep the bytes for entire input. That's okay if memory is 256 MB. But we also have output. Might be okay.
But we can also process test case by test case using reading line by line which uses less memory. I'll go with line by line for simplicity and moderate performance.
But we need to be careful about Python's recursion? Not needed.
We'll implement using sys.stdin.buffer.readline. However, we need to skip blank lines if any; but likely none. So we can do:
import sys
def main():
import sys
data = sys.stdin.buffer
t = int(data.readline())
out = []
for _ in range(t):
# read N M
while True:
line = data.readline()
if line.strip():
break
n_m = line.split()
if len(n_m) < 2:
# maybe the line only had one? then read next? unlikely.
next_line = data.readline()
n_m += next_line.split()
n = int(n_m[0]); m = int(n_m[1])
res = []
for i in range(n):
best_val = 10**9
best_idx = 0
for shop in range(1, m+1):
# read line with three ints
while True:
line = data.readline()
if line.strip():
break
a,b,c = map(int, line.split())
prod = (100 - a) * (100 - b) * (100 - c)
if prod < best_val:
best_val = prod
best_idx = shop
res.append(str(best_idx))
out.append(' '.join(res))
sys.stdout.write('\n'.join(out))
if name == "main":
main()
This should work.
But we need to consider that the input may be such that there are extra spaces or multiple spaces; but splitting handles.
Potential performance: For each line, we call map(int, line.split()). That creates a list of strings then map to ints. Could be slower. We could parse three ints manually from bytes to avoid creating list and map? But it's okay.
Another improvement: Use .split() to get three tokens and convert to int via int(). That's fine.
Given that N and M up to 1000, total lines per test case is N*M <= 1e6. For each line we do split and three int conversions. That's 3 million int conversions per test case. That's okay in Python if the input is not too large? 3 million int conversions might take about 0.5-1 second. With T maybe 2-3, still okay.
But we also have T test cases, but total lines across tests is limited by total input size. The problem statement didn't give upper bound on T, but maybe T small. I'll assume it's fine.
We need to output for each test case, the N space-separated shop indices.
The sample output shows each test case's output on a separate line. In sample, they had "3" for first test case, then newline, then "2 1" for second. Actually sample output:
3
2 1
So there's a newline after each test case. So join with spaces and then separate test cases by newline.
Implementation as above.
Edge Cases:
-
N=0? Not possible, min 1.
-
M=0? Not possible.
-
Discount values can be 100, product becomes 0, so best.
-
If product equals best from earlier shop, we keep earlier (since only update when strictly less).
Check tie: example: discounts produce same product. For product 1, shop1 product=1000, shop2 product=1000. With our update only when prod < best, shop1 will be kept. So output lower index.
Alright.
Now, one more nuance: The problem says: "Each shop has a successive discount of order-3 on each of the N products." Means each shop provides three successive discounts for each product. So we read three ints per shop per product.
Thus solution.
Potential pitfalls: Using (100 - a)(100 - b)(100 - c) could overflow 32-bit? It's at most 100^3=1e6, so fits in Python int easily.
But we need to ensure we use integer arithmetic. It's fine.
Now confirm sample:
First test: n=1,m=3. Process shops: line1:20 20 50 -> product=808050=320000, best_idx=1, best_val=320000. line2:30 20 0 -> product=7080100=560000, not < 320000, no update. line3:60 50 0 -> product=4050100=200000, <320000 -> update idx=3. So result [3]. Output "3".
Second test: n=2,m=2. Item1: shop1:20 20 20 ->808080=512000, idx1 best=512000. shop2:30 20 40 ->708060=336000 <512000 -> idx2. So item1 best=2. Item2: shop1:10 100 90 ->90010=0 -> best_val initial large, update idx1 best_val=0. shop2:35 60 50 ->654050=130000, not <0. So item2 best=1. Output "2 1".
Matches.
Thus solution correct.
Now, about performance: Use sys.stdin.buffer.readline inside loops; for each line we call strip() to skip blank lines. But if there are no blank lines, this check is wasted. We can simply assume no blank lines and directly split, but to be robust we keep strip? However, calling strip() creates a new bytes object, which adds overhead. We could check if line contains b'\n' only? But if there are blank lines, they'd be b'\n', so line.strip() would be empty. But if there are no blank lines, we can skip the check. Usually contest inputs have no blank lines. So we can read without skipping:
line = data.readline()
if not line: break # but that shouldn't happen.
But to be safe, we can do:
line = data.readline()
while line and line.strip() == b'': line = data.readline()
But to speed, we might assume no blank lines. I'll keep the simple: line = data.readline(); a,b,c = map(int, line.split()) . If there are blank lines, it will error because split returns fewer than 3. So better to include check if necessary. However, in problem input, there shouldn't be blank lines. So I'll just read directly.
But there is a nuance: After reading N and M line, the next lines are exactly M lines per product. So we can read sequentially.
Thus final code:
import sys
def solve():
import sys
data = sys.stdin.buffer
t = int(data.readline())
out = []
for _ in range(t):
# read N M line; might have trailing newline; but we split.
while True:
line = data.readline()
if line.strip():
break
n, m = map(int, line.split())
res = []
for i in range(n):
best_val = 10**9
best_idx = 0
for shop in range(1, m+1):
line = data.readline()
# Might be blank lines? we skip if any.
while line.strip() == b'':
line = data.readline()
a,b,c = map(int, line.split())
prod = (100 - a) * (100 - b) * (100 - c)
if prod < best_val:
best_val = prod
best_idx = shop
res.append(str(best_idx))
out.append(' '.join(res))
sys.stdout.write('\n'.join(out))
if name == "main":
solve()
That should work.
Alternatively, we can use sys.stdin.buffer.read() with iterator to avoid the while loops for blank lines. But this is fine.
Now let's consider potential integer overflow? Not.
Thus solution done.
But wait: The problem statement says "You may assume that the base price of each item is same on all shops." So base price is same for a given item across shops. But base price might differ per item. However, we only compare across shops for each item individually, so base price cancels out.
Thus answer.
Now, I'd like to double-check the problem: "Each item is available on M shops . Being the Valentine Season, shops have the products on a discounted price. But, the discounts are in the form of successive discounts. Each shop has a successive discount of order-3 on each of the N products." So we treat each item independently.
Now, is there any trick about rounding? No, because discounts are percentages, and final price might involve fractions, but they likely expect that we compare using the product of (100 - discount) to avoid floating point. Because base price is same, the ordering is preserved. So integer multiplication works.
Thus final answer.
I'll produce final output with explanation.
Now, I'll write the final solution in the answer. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer
t = int(data.readline())
out_lines = []
for _ in range(t):
# read N and M; skip possible blank lines
while True:
line = data.readline()
if line.strip():
break
n, m = map(int, line.split())
item_results = []
for _ in range(n):
best_val = 10**9 # larger than any possible product
best_shop = 0
for shop in range(1, m + 1):
# read the three discounts for this shop
while True:
line = data.readline()
if line.strip():
break
a, b, c = map(int, line.split())
# effective factor (100-a)*(100-b)*(100-c) – smaller is cheaper
prod = (100 - a) * (100 - b) * (100 - c)
if prod < best_val:
best_val = prod
best_shop = shop
item_results.append(str(best_shop))
out_lines.append(' '.join(item_results))
sys.stdout.write('\n'.join(out_lines))
if name == "main":
solve()