In Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by a and the ticket number — by b, then a ticket is described by the ordered pair of numbers (a, b).
The walruses believe that a ticket is lucky if a * b = rev(a) * rev(b). The function rev(x) reverses a number written in the decimal system, at that the leading zeroes disappear. For example, rev(12343) = 34321, rev(1200) = 21.
The Public Transport Management Committee wants to release x series, each containing y tickets, so that at least w lucky tickets were released and the total number of released tickets (x * y) were minimum. The series are numbered from 1 to x inclusive. The tickets in each series are numbered from 1 to y inclusive. The Transport Committee cannot release more than maxx series and more than maxy tickets in one series.
Input
The first line contains three integers maxx, maxy, w (1 ≤ maxx, maxy ≤ 105, 1 ≤ w ≤ 107).
Output
Print on a single line two space-separated numbers, the x and the y. If there are several possible variants, print any of them. If such x and y do not exist, print a single number - 1.
Examples
Input
2 2 1
Output
1 1
Input
132 10 35
Output
7 5
Input
5 18 1000
Output
-1
Input
48 132 235
Output
22 111
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given maxx, maxy, w. We need to choose x (1 ≤ x ≤ maxx) and y (1 ≤ y ≤ maxy) such that the number of lucky tickets among tickets (a,b) with 1 ≤ a ≤ x, 1 ≤ b ≤ y is at least w. Among those (x,y) that satisfy, we want to minimize x*y. If multiple, any. If no such, output -1.
Definition: a ticket (a,b) is lucky if a * b = rev(a) * rev(b). rev(x) is integer formed by reversing decimal digits of x, dropping leading zeros. So rev(x) = reverse of x's digits.
We need to count for a given rectangle (x,y) the number of pairs (a,b) with 1 ≤ a ≤ x, 1 ≤ b ≤ y such that a * b = rev(a) * rev(b).
Observation: condition can be rearranged. Let f(a) = a / rev(a) perhaps? But note that a and rev(a) are integers. Condition: a * b = rev(a) * rev(b) <=> a / rev(a) = rev(b) / b. But careful with division: rev(a) might be zero? No, rev(a) > 0 for positive a because a >=1, reversing yields positive, but maybe leading zeros vanish, so rev(10) =1, rev(100)=1, etc. So rev(a) ≥ 1. So we can take fraction.
Define ratio r(a) = a / rev(a) as a rational number in reduced form. Then condition becomes r(a) = rev(b)/b = 1 / r(b) perhaps? Actually rev(b)/b = 1 / (b/rev(b)) = 1 / r(b). So condition: a/rev(a) = rev(b)/b => a/rev(a) = 1/(b/rev(b)) => a/rev(a) * b/rev(b) = 1 => (a/rev(a)) * (b/rev(b)) = 1. So equivalently, r(a) * r(b) = 1.
Thus lucky if and only if r(a) * r(b) = 1. So r(b) = 1 / r(a). So essentially we need pairs where the ratio of a to its reverse is reciprocal to that of b.
Thus we can compute for each integer n (1 to max maxx,maxy) the value r = (n / rev(n)) as a reduced fraction p/q (gcd(p,q)=1). Then lucky condition becomes (p1/q1) * (p2/q2) = 1 => p1 p2 = q1 q2 => p1/q1 = q2/p2 => reduced fraction of a is reciprocal of reduced fraction of b.
So we can map each n to a pair (p,q) with gcd(p,q)=1, such that n/rev(n) = p/q. Then the condition for (a,b) is (p_a,q_a) = (q_b,p_b) (since reciprocal). So essentially we need a's fraction (p,q) and b's fraction (q,p).
Therefore, the count of lucky tickets in rectangle (x,y) is sum over all pairs of fractions where (p,q) appears in rows (a) and (q,p) appears in columns (b). More precisely, for each fraction type (p,q), let A_x(p,q) = number of a in [1,x] such that (a/rev(a)) reduces to (p,q). Similarly, B_y(p,q) = number of b in [1,y] such that (b/rev(b)) reduces to (p,q). Then number of lucky pairs = sum_{all fractions} A_x(p,q) * B_y(q,p). (Because for each a of type (p,q) and b of type (q,p) they form lucky pair). Note that if (p,q) = (q,p) (i.e., p=q), then the pair contributes A_x(p,p) * B_y(p,p). But that's fine.
Thus the count depends on distributions of fractions.
We need to find x≤maxx, y≤maxy to achieve at least w with minimal x*y.
Constraints: maxx,maxy ≤ 1e5, w up to 1e7. So we can compute for all numbers up to N = max(maxx,maxy) (<=1e5) their fraction type. Then we need to consider possible x and y. Brute force over all x (up to 1e5) and y (up to 1e5) would be 1e10, too many.
We need a smarter approach.
Observation: The count function for fixed x, as y increases, B_y increases, so total count is monotonic non-decreasing in both x and y. So we can think of two-pointer or scanning. We need to minimize product x*y. Classic problem: given monotonic functions, find minimal rectangle area covering a threshold.
But we need to compute count quickly for many (x,y) combinations. We can precompute for each a the fraction, store in array. For each x we have a multiset of fractions for rows, and we need to know for given y the sum of A_x(p,q) * B_y(q,p). This can be computed if we maintain counts as we increase x or y.
We can consider iterating over x from 1 to maxx, and maintain an array of row counts per fraction. Then we need to find minimal y such that count >= w for that x. Since as y increases, count increases. So for each x, we could binary search y. But we need to answer queries: for a given x and y, compute count. If we can answer queries fast (like O(sqrt N) or O(log N) per query) then total complexity might be acceptable: maxx * log maxy * queryTime. maxx=1e5, log=~17, queryTime if O(number of distinct fractions?) might be high.
We need efficient structure.
Alternatively, we can iterate y and find minimal x for each y. Since product symmetric, we can treat min product. Might do two-pointer: start with x = maxx, y = 1? Not exactly.
We can note that the total distinct fractions are limited. For each n up to 1e5, compute rev(n) and fraction p/q = n/rev(n) simplified. n up to 1e5, so p and q values? n up to 1e5, rev(n) also up to maybe 10^5? Actually rev can be up to 99999 => 99999, so p and q up to 1e5. But after reduction they can be up to 1e5/gcd. So distinct fractions count at most N. Probably less than N.
We can precompute for each y from 1 to maxy the column counts by fraction. Actually, we could precompute for each y the count of b's with each fraction. But storing full matrix (distinct fractions) per y is heavy. However, we can compute prefix arrays: For each fraction, we could store a list of y indices where it occurs, and use Fenwick tree to add contributions when increasing y? Let's think.
Alternative approach: Since N=1e5, we can precompute for each number its fraction as a pair (p,q). Then we can create arrays rowCount[frac] and colCount[frac]. As we sweep x and y, we can update rowCount when we add a new a, and update total lucky count by adding contributions from this new a with all b's currently in colCount. Similarly, if we sweep y and maintain colCount, we can update total count when adding a new b.
So consider two-dimensional optimization: We need to find minimal x*y such that count(x,y) >= w. We could use a two-pointer technique on either dimension. For each x, we could compute minimal y by increasing y from 1 to maxy, and maintain cumulative contributions. But we need to do for all x, not individually.
We can do something like: fix x, then start y from previous y (since as x increases, the required y likely decreases or stays?). Actually, if we increase x, count increases for any fixed y, so the minimal y needed for that x to reach w is non-increasing as x increases. So we can use a sliding window: Start with x = maxx, y = 1, count = current (x,y). But we need to know minimal product; typical approach: For each x from 1..maxx, find minimal y such that count(x,y) >= w, then compute product, take min. Since y needed decreases as x increases, we can start y at some value and adjust downwards? Actually count(x,y) monotonic in both. As x increases, the function count(x,y) for a fixed y is larger. So the minimal y to achieve w is non-increasing: as we have more rows, we need fewer columns. So we can maintain a pointer y starting from maxy (or from 1) and decrease when needed? Typically, if we iterate x from 1 to maxx, the required y might start high and then drop. But we can maintain current y such that for current x, count(x,y) is just at least w, and then for next x (higher), count(x,y) will be at least w (since x increased) maybe even more, so we can possibly decrease y while still meeting w. So we can start y = maxy and compute count(1, maxy) maybe not enough? Actually we want to find for each x minimal y, so we can start y = maxy, and for each x, while count(x,y-1) >= w, decrease y. This ensures that for each x, y is minimal such that count(x,y) >= w. Then compute product, track min. The complexity is O(maxx + maxy) updates if we can update count efficiently when x increments (adding a row) or when y decrements (removing a column). But decrementing y (removing a column) is not as straightforward to maintain count because we need to subtract contributions from that column. However, we can maintain a data structure that supports addition of a row and removal of a column, and we need to compute count = sum_{fractions} rowCount[f] * colCount[reciprocal(f)]. Adding a row: increase rowCount for its fraction, then add to totalCount the colCount[reciprocal fraction] (since each existing column b of type reciprocal pairs with new row). Similarly, removing a column: decrease colCount for its fraction, then subtract from totalCount the rowCount[reciprocal fraction] (since those pairs are lost). So we can maintain totalCount dynamically with O(1) per addition/removal if we have arrays rowCount and colCount indexed by fraction ID, and a mapping from fraction to its reciprocal fraction ID. So that works! Provided we have a mapping of each fraction to an ID and its reciprocal fraction ID.
Thus we can perform a two-pointer (or sliding window) scan:
We want to find, for each x (from 1 to maxx), the minimal y (from 1 to maxy) such that count(x,y) >= w. Since as x increases, minimal y is non-increasing, we can start with x = 0? Actually we need to start with some initial state. Approach:
Initialize rowCount[all]=0, colCount[all]=0. totalCount=0.
Set y = maxy (or maybe 1?). To get the minimal y for each x, we need to ensure that for a given x, we have colCount representing all b from 1..y. Since we want to be able to decrease y (remove columns) as x increases, we should start with y = maxy, and pre-fill colCount with all columns from 1..maxy (so initially y = maxy, and rowCount empty (x=0)). Then for x = 1..maxx, we add row a = x. After adding, totalCount increases. Then while y > 0 and totalCount - (contribution of columns = y?) Actually we need to check if we can reduce y while still totalCount >= w. But careful: after adding row x, we have current y (starting from maxy). We can attempt to decrease y by removing columns (from y down to 1) as long as after removing a column, totalCount remains >= w. However, when we remove column y, we are effectively considering the rectangle (x, y-1). So we need to check if after removing, totalCount >= w. But we want to have the minimal y for this x. So we can while y > 0 and if after removing column y (i.e., if we simulated removal) the totalCount would still be >= w, we actually remove it and decrement y. This yields the minimal y for current x.
But we must also consider that maybe totalCount is already < w for current (x,y) after adding row x. Then we cannot reduce y; in fact we need to increase x further to maybe later achieve w (since y is already at max). If even at x=maxx and y=maxy the count is < w, then answer -1.
Thus algorithm:
Precompute for each number i from 1 to max(maxx, maxy) its fraction (p,q) reduced, and its reciprocal fraction (q,p). Store them in arrays: frac[i] = id of its fraction; recip[i] = id of fraction (q,p) (which is the fraction type needed for pairing). Actually we need mapping from fraction to id. So compute for each i:
rev_i = rev(i)
Compute p = i / g, q = rev_i / g, where g = gcd(i, rev_i). So fraction = (p,q). We need an ID for each distinct (p,q). Also we need reciprocal ID: for (p,q), reciprocal is (q,p). So we can precompute for each fraction id, its reciprocal id. Then for each number i, we set id_i, recip_id_i = reciprocal of id_i.
Then we can maintain two count arrays: rowCnt[total_ids] and colCnt[total_ids]. Initially rowCnt all 0, colCnt all 0.
First, populate colCnt for all b from 1 to maxy: for each b, colCnt[id_b]++ (but we need colCnt for fractions; note we will use colCnt[ fraction(b) ] ). However, we also need to know totalCount initially? But we will start with x=0, y = maxy. Initially rowCnt empty, totalCount = 0 (since no rows). Then we will add rows one by one, and after each addition, we will try to shrink y.
But we also need to maintain totalCount as we add rows and remove columns. The initial totalCount = 0 because no rows. That's fine.
Procedure:
Precompute for each i up to max(maxx, maxy): rev_i, fraction id, reciprocal id.
Let total_ids = number of distinct fractions.
Initialize rowCnt[ids] = 0.
Initialize colCnt[ids] = 0.
For b from 1 to maxy: colCnt[ id_b ]++.
(But we also may later need to remove columns from the right. However, we need to keep colCnt reflecting the current y (columns 1..y). So if we initially set colCnt for all b, that corresponds to y = maxy. Then later we will remove columns as we decrement y. So we need a way to know which fraction each b has, so we can when removing column y, decrement colCnt[ id_y ].
So we need arrays: colFrac[maxy+1] = id of b.
Similarly, for rows as we increase x, we add a = x: rowCnt[ id_a ]++. And we update totalCount: totalCount += colCnt[ recip_id_a ] (because new row a pairs with existing columns b that have fraction = recip(id_a) i.e., (q,p) ) . So we do that.
For removal of column y (the current highest column index), we need to: totalCount -= rowCnt[ recip_id_y ] (because we are removing column b with id = id_y; its pairs with existing rows are rowCnt[ recip(id_y) ]). Then decrement colCnt[ id_y ].
We need to ensure we don't remove below y=1, obviously.
Now scanning:
Set x = 0, y = maxy, totalCount = 0.
best_product = INF, best_x, best_y = -1.
// Now we have rectangle (x, y)
// While y >= 1 and totalCount >= w, we can try to reduce y. But careful: we want to check if after removing column y, totalCount would still be >= w. So we need to compute new totalCount after removal. However, we can simulate: if totalCount - rowCnt[ recip_id[y] ] >= w, then we can remove column y, update totalCount and colCnt and y--. But careful: rowCnt[ recip_id[y] ] is the number of rows with fraction equal to reciprocal of column y. That's correct because the pairs lost are exactly the number of rows that pair with this column. However, note that when we remove column y, we also lose pairs where the column is the same as this column? Actually totalCount is sum_{f} rowCnt[f] * colCnt[recip(f)]. If we decrement colCnt[ id_y ], the reduction in totalCount is rowCnt[ recip(id_y) ] (since recip(id_y) = fraction that pairs with this column). Because colCnt[ id_y ] is multiplied by rowCnt[ recip(id_y) ]. So indeed the reduction is rowCnt[ recip(id_y) ]. Provided rowCnt remains unchanged. So condition: if totalCount - rowCnt[ recip_id[y] ] >= w, then we can remove it. But careful: totalCount after removal would be totalCount - rowCnt[ recip_id[y] ]. So we can test that.
However, we need to also consider that there could be the scenario where rowCnt[ recip_id[y] ] is not accurate because it includes the row we just added? That's fine; it's the current row count. So we can do:
while y > 0 and totalCount - rowCnt[ recip_id[y] ] >= w:
totalCount -= rowCnt[ recip_id[y] ]
colCnt[ id[y] ]--
y--
But after we decrement y, we need to update the condition again because rowCnt[ recip_id[y] ] might be different for new y? Actually we are removing from the high end. After we reduce y, we have a new y. We check again.
Important: We must ensure that the columns we remove are those with index y, i.e., the current highest column. Our initial colCnt includes columns 1..maxy. As we remove, we are effectively decreasing y, so columns from y+1 to maxy are not included. So we need to process in decreasing order: start y = maxy; remove column y; then y becomes y-1. This is consistent.
After this while loop, we have y minimal for current x such that totalCount >= w (if totalCount >= w). If totalCount >= w, then we have a valid rectangle (x, y). Compute product = x * y. If product < best_product, update best.
But we must also consider the possibility that after adding row x, totalCount might still be < w. Then we cannot reduce y (since y already max? Actually y = current, maybe already less than maxy due to previous reductions). But if totalCount < w, then this (x,y) does not meet threshold, so we skip product update. However, we might need to later increase x to get more rows, which might increase totalCount. So we continue.
At the end of loop over x, if best_product remains INF, answer -1 else output best_x, best_y.
But is it guaranteed that this scanning yields the minimal product? We need to verify the monotonic property: For a fixed x, as we increase y, totalCount increases (since we add columns). Conversely, for fixed y, as we increase x, totalCount increases. So the set of (x,y) where totalCount >= w is an up-set (if (x,y) works then any (x', y') with x' >= x, y' >= y also works). This is typical for monotone 2D grid. In such a monotone region, the minimal product (by area) can be found by scanning along the "boundary". The approach of iterating x increasing and adjusting y decreasing to stay on the lower envelope of the region yields the minimal product. This is similar to typical problem "find minimum xy such that f(x,y) >= w" with monotonic f. The method: start with y = maxy, then for each x from 1 to maxx, increase x, update count, and while f(x, y-1) >= w decrease y. This ensures that for each x, we get the minimal y for which f(x,y) >= w. Since as x increases, minimal y is non-increasing, the while loop that only decreases y is valid. This method will examine all candidate pairs on the "Pareto frontier" and thus find minimum product. It works because for each x, we find the smallest y that works; and for any (x,y) that works, there is some x' (maybe smaller) with minimal y' for that x' that yields product <=? Actually we consider each x; the minimal product might occur at some x, and we are checking all possible x's minimal y. Since for each x we take minimal y, the minimal product will be among those. However, we must ensure that when we decrease y, we are considering rectangles where y is the exact upper bound; we might miss some pairs where y is not minimal for that x but product could be smaller? For a given x, product xy increases with y. So minimal product for that x is achieved at minimal y that works. So indeed only need to consider for each x the minimal y. So scanning all x and taking minimal y yields candidate set containing the global optimum.
One nuance: The minimal y for a given x might be 0? but y must be at least 1. So we stop when y=0? Actually if totalCount >= w with y=0 (i.e., no columns) that would be impossible because columns count at least 1. So we treat y >=1.
Now about the condition in while loop: we used totalCount - rowCnt[recip_id[y]] >= w. But careful: totalCount currently corresponds to rectangle (x, y). However, rowCnt and colCnt reflect exactly that rectangle (since we added rows up to x, and columns up to y). After we remove column y, we get rectangle (x, y-1) and its totalCount would be totalCount - rowCnt[recip_id[y]]. So we compare that with w. If it's still >= w, we can perform removal and continue. However, we need to ensure that rowCnt[recip_id[y]] is correct after we possibly have just removed some columns? Since we are removing from the end, rowCnt hasn't changed, so it's fine. However, note that colCnt is used to compute totalCount updates when adding rows. That's consistent.
But one more nuance: When we remove column y, we also affect the condition for further removals: totalCount updates, colCnt updates. So while loop works.
Edge Cases: It could happen that after adding row x, totalCount >= w, and then we remove columns until totalCount would drop below w. The while condition checks if after removal, totalCount' >= w. So we stop when removal would make it < w. So we end with smallest y such that totalCount >= w. That's exactly what we want.
Now about initial colCnt: we set colCnt for all b=1..maxy. That's fine, but we start with x=0, totalCount=0. Then we iterate x=1..maxx, adding rows. At each step, after adding row x, we try to reduce y. But we also need to consider that initially y = maxy is fixed, but there could be case where even with x=0 and y=some lower value we could have totalCount>=w? But x must be at least 1. So we start from x=0 and will find first x where totalCount becomes >=w after addition.
One more nuance: The algorithm only decreases y. But is it always true that minimal y for x is non-increasing? Suppose for x=5, minimal y is 10. For x=6, minimal y could be 11? No, because adding more rows cannot reduce the count for a fixed y, so if (5,10) works, (6,10) also works, so minimal y for x=6 ≤ 10. So non-increasing. So we only need to decrease y, never increase. So algorithm works.
Now complexity: O(maxx + maxy) updates, each update is O(1). So overall O(N). Good.
But we need to ensure the mapping of fractions to IDs and reciprocal IDs.
Implementation details:
Compute rev for numbers up to M = max(maxx, maxy). M ≤ 1e5. We can compute rev by converting to string or by numeric reversal. Since M ≤ 1e5, doing numeric reversal per number is fine.
For each n, compute r = rev(n). Compute g = gcd(n, r). p = n / g, q = r / g.
We need to map (p,q) to an integer ID. Since p,q can be up to maybe 1e5? Actually n up to 1e5, rev up to 1e5, so p,q up to 1e5. Could use a map from pair to id. Number of distinct fractions ≤ M. So using unordered_map or map is okay. But we also need reciprocal mapping: for each id, store reciprocal id. For a fraction (p,q), its reciprocal is (q,p). We need to ensure that (q,p) also gets an ID (may be same as (p,q) if p=q). So we can process all numbers first, collect all (p,q) and (q,p) via inserting into map. Or we can simply for each n compute both fractions and insert into map; after all numbers processed, assign IDs. Then for each number we can retrieve id of its own fraction and reciprocal fraction id by looking up (p,q) and (q,p). However, during scanning we need recip_id for each number quickly. So we can precompute for each n: id_n = map[(p,q)], recip_id_n = map[(q,p)].
Also note that when we compute rev(n), if n has trailing zeros, rev(n) could be smaller. That's fine.
Implementation steps:
Read maxx, maxy, w.
Let M = max(maxx, maxy). Compute for i=1..M: rev_i, gcd, p = i/g, q = rev_i/g.
Use an efficient method: rev function:
int rev(int x) {
int r = 0;
while(x) { r = r*10 + x%10; x/=10; }
return r;
}
Use a map<pair<int,int>, int> mp. But pair<int,int> can be hashed with custom hash or use map. Since M=1e5, map (ordered) is fine, O(N log N). But we can also use unordered_map with hash for pair. However, to avoid potential collisions, we can use map. O(N log N) is acceptable.
Alternatively, we can use a more clever encoding: since p and q up to 1e5, we could use long long key = p * (1e5+1) + q. But we need to ensure uniqueness. That's fine: p,q up to 1e5? Actually p could be up to 1e5 (if n=1e5 and rev=1, then p=1e5, q=1). So we can encode as p200000+ q (or p200001+ q). But safe to use map.
I'll use unordered_map with a hash function for pair<int,int> (or use map for simplicity).
First pass: For i=1..M, compute (p,q) and also (q,p) but we can just insert (p,q). At the end, assign IDs to all distinct pairs. But we also need reciprocal ID. So after building the map, we can iterate over its entries and assign ID. Then we need a way to get ID of a given pair later. So after assigning IDs, we need to be able to look up ID for a pair quickly. Since we have the map already, we can just use it. But when we later need recip_id for i, we can compute (q,p) and look up in map. That's fine.
However, we need to ensure that (q,p) is in the map. It might not be if no number yields that fraction. But still we need to know its ID for pairing? Actually if we have a fraction (p,q) that appears in rows, but its reciprocal (q,p) may not appear in columns. In that case, colCnt[recip_id] would be 0, so contributions are zero. However, we need recip_id as an index for colCnt. It's okay if that ID exists. But if (q,p) was never inserted into map because no number i has that fraction, then our map won't have it, and lookup would fail. But we still need to be able to reference that ID for updates: when we add a row with fraction (p,q), we need to add colCnt[recip_id] to totalCount, where recip_id corresponds to fraction (q,p). If (q,p) never appears in numbers, colCnt will always be 0, but we still need a valid index to access colCnt array; we could treat it as a separate ID. However, to maintain consistency, we should ensure that all reciprocal fractions that might be referenced (even if they don't appear in numbers) have an ID. But do they need to? Only if we ever need to index colCnt at that ID. When we add a row, we add colCnt[recip_id]. If recip_id is not present (i.e., no number with that fraction exists), colCnt at that index is 0, and it's fine. But we need to have that ID defined so we can allocate an array of size total distinct fractions including both directions? However, we can simply, when we build the map, we insert both (p,q) and (q,p) for each number? That would cover many, but what if a fraction (q,p) never occurs? Could it be that some reciprocal pair never appears? Possibly. But if it never appears, we may never need to index it because colCnt[recip_id] would be zero, but we still need to know recip_id to compute the addition. However, if we don't have an ID for that fraction, we cannot do colCnt[ID] because ID is undefined. So we need to ensure that for every fraction that might be referenced as a reciprocal of some existing fraction, we have an ID. That is: if there exists a number with fraction (p,q), then its reciprocal (q,p) must be assigned an ID, because we will need to index colCnt for that fraction. Even if no number has that fraction, we need to have that ID. So we must insert both (p,q) and (q,p) into the map while processing numbers. But note that for numbers, we only have fractions for numbers in [1,M]. So we can when processing each i, compute (p,q), and also its reciprocal (q,p). Insert both into the map. That will ensure that all reciprocal fractions that could be referenced (since any fraction that appears as (p,q) for some i, its reciprocal is (q,p) and will be inserted). So after processing all i, the map will contain all fractions that appear either directly or as reciprocal of an existing number. However, there might be a fraction that does not appear in either but is needed? Not needed because if no number has that fraction, we never need to index it. And if some number has fraction (p,q), we inserted its reciprocal, so it's covered.
But careful: What about a fraction that appears only as reciprocal but not directly? That's fine; we inserted it. So after this step, we have a set of fractions that are either from numbers or their reciprocals. This set size is at most 2 * distinct fractions from numbers? Actually each number gives two fractions, but many may be duplicates. So total distinct pairs at most 2 * number of distinct fractions from numbers? Actually each distinct fraction from numbers yields its reciprocal, which could be same (if p=q) or distinct. So total distinct <= 2 * number of distinct fractions from numbers. Since number of distinct fractions from numbers ≤ M, total distinct ≤ 2M = 2e5, still fine.
Thus algorithm: For i=1..M, compute p,q, insert (p,q) and (q,p) into map. Later, assign IDs sequentially.
Then for i=1..M, retrieve id[i] = mp[(p,q)], recip_id[i] = mp[(q,p)].
But wait: We need to ensure that when we later process i only up to maxx or maxy, we have these arrays defined for i up to M. So we compute for all i from 1 to M. Since M = max(maxx, maxy). Good.
Now we need arrays rowCnt and colCnt of size total_ids. Initialize to zero.
Pre-filling colCnt for b=1..maxy: we need to add each b's fraction to colCnt. So we loop b=1..maxy, colCnt[ id[b] ]++.
But careful: When we later remove columns, we need to know for each b its id and recip_id. So we store arrays id[i] and recip[i] for all i up to M.
Now the scanning algorithm:
Initialize:
x = 0
y = maxy
totalCount = 0
rowCnt zeros
colCnt as filled (since we set all columns initially)
But note: Initially we have rows empty, so totalCount=0. That's fine.
Iterate x from 1 to maxx:
// add row x
totalCount += colCnt[ recip[x] ] // because new row pairs with existing columns of reciprocal fraction
rowCnt[ id[x] ]++
code
// attempt to reduce y
while y >= 1 and totalCount - rowCnt[ recip[y] ] >= w:
totalCount -= rowCnt[ recip[y] ]
colCnt[ id[y] ]--
y--
// after while, if totalCount >= w, then (x,y) is valid with minimal y for this x
if totalCount >= w:
if x * y < best_product:
best_product = x * y
best_x = x
best_y = y
After loop, if best_product is INF: print -1 else print best_x best_y.
Check examples.
Example 1:
maxx=2, maxy=2, w=1.
First compute fractions:
Numbers 1..2.
rev(1)=1, p/q=1/1 => (1,1)
rev(2)=2, p/q=2/2=1/1 => (1,1) also.
So only fraction (1,1). Reciprocal is same.
So id[1]=id[2] = ID for (1,1). recip same.
rowCnt[ID] becomes 2
Now while y>=1 and totalCount - rowCnt[recip[1]] >=1? recip[1]=ID, rowCnt[ID]=2, totalCount-2=0, not >=1. So no removal.
totalCount=2 >=1, product=2*1=2 > best=1, so keep best=1.
Thus answer 1 1. OK.
Example 2:
maxx=132, maxy=10, w=35.
Let's simulate quickly to see if expected output 7 5.
We need to verify algorithm yields that. We'll trust.
Example 3: maxx=5, maxy=18, w=1000. Probably not possible, output -1.
Example 4: 48 132 235 -> output 22 111.
We'll test with code later.
But there might be issues: The algorithm uses colCnt initially full of all b up to maxy. Then we add rows and possibly reduce y. However, note that when we reduce y, we are removing columns from the end (largest b). But is it guaranteed that the minimal y for a given x is achieved by taking columns from 1..y (lowest indices)? Because the definition of rectangle is a from 1..x, b from 1..y. So it's exactly the set of first y columns (b=1..y). Our algorithm always maintains columns as a prefix from 1 to y. That's correct. The rectangle must be of that form: series numbered 1..x and tickets in series 1..y. So it's the initial segment of both dimensions. So we are correct: we consider y as the number of tickets per series (max ticket number), not arbitrary set. So rectangle is axis-aligned and starts at 1 for both a and b. So our approach is correct.
Now, we must ensure that when we remove column y, we are removing the highest index among currently included columns, i.e., we are effectively decreasing y. This is valid because we want the smallest y such that the prefix rectangle works. Since the count function is monotonic in y (increasing as y increases), the minimal y for given x is indeed the smallest y such that count(x,y) >= w. So we need to shrink from maxy downward until we cannot.
One nuance: Could there be a situation where for a given x, the minimal y that works is not attained by taking the first y columns because the distribution of lucky tickets might not be monotonic? But note: count(x,y) is defined as number of lucky pairs with a<=x, b<=y. As y increases, we add more columns (b values). So it's monotonic non-decreasing. So yes, minimal y such that count >= w will be a prefix. So it's correct.
Thus algorithm seems correct.
Now we need to ensure our updates maintain the correct totalCount for the current rectangle (x, y). Initially we set colCnt for b=1..maxy and rowCnt empty (x=0). Then we add rows one by one. After each row addition, we potentially remove columns from the end. So at any point, rowCnt represents rows 1..x, and colCnt represents columns 1..y. Our totalCount is maintained as sum_{f} rowCnt[f] * colCnt[recip(f)]. This matches the count for the rectangle (x,y). Because each pair (a,b) with a in rows, b in columns contributes if fraction(a) and fraction(b) are reciprocal. And we maintain that sum by updating when adding rows or columns.
But careful: When we remove column y, we subtract rowCnt[recip[y]] from totalCount. Is that always accurate? Let's derive: totalCount = sum_{f} rowCnt[f] * colCnt[recip(f)]. When we decrement colCnt[ id[y] ] by 1, the term in the sum that changes is for f = recip(id[y])? Actually we need to see which f gets multiplied by colCnt[?]. Suppose column b has fraction f_b = id[b]. It contributes to totalCount through rowCnt[ recip(f_b) ] because colCnt[ f_b ] is multiplied by rowCnt[ recip(f_b) ] in the sum: total = sum_{f} rowCnt[f] * colCnt[recip(f)]? Wait check: If we denote fractions for rows as R and for columns as C, then lucky condition: row fraction (p,q) and column fraction (q,p). So for a row with fraction (p,q), it pairs with columns having fraction (q,p). So totalCount = sum_{all fractions f} rowCnt[f] * colCnt[recip(f)], where recip(f) is the fraction (q,p) if f=(p,q). Alternatively, we could also compute as sum_{all fractions f} colCnt[f] * rowCnt[recip(f)]. Both are symmetric.
So if we have colCnt indexed by fraction f, then totalCount = sum_{f} rowCnt[recip(f)] * colCnt[f]? Let's align: For each column with fraction f, it pairs with rows with fraction recip(f). So totalCount = sum_{f} colCnt[f] * rowCnt[recip(f)]. That's simpler: iterate over column fractions. So if we maintain colCnt[f] for each f, and rowCnt[g] for each g, totalCount = sum_{f} colCnt[f] * rowCnt[recip(f)]. That's equivalent to sum_{g} rowCnt[g] * colCnt[recip(g)]. So both are fine.
Now, when we add a row with fraction f_r, we need to increase totalCount by colCnt[ recip(f_r) ] because this new row will pair with each existing column whose fraction is recip(f_r). That matches our code: totalCount += colCnt[ recip[x] ].
When we remove a column with fraction f_c, we need to decrease totalCount by rowCnt[ recip(f_c) ] because we are removing those pairs. So we subtract rowCnt[ recip[y] ]. That's exactly what we do.
Thus it's consistent.
Now, we need to store for each number i: id[i] (fraction of i), recip_id[i] (fraction that pairs with i, i.e., reciprocal of its fraction). But careful: In the update for row addition, we used recip[x] meaning the fraction that pairs with row's fraction. For row a, its fraction is f_a = id[a]. Pairs with columns of fraction recip_f = recip_id[a]. So we use colCnt[ recip_id[a] ]. That's fine.
Similarly, for column removal, we use recip_id[y] for the pairing: column b's fraction is f_b = id[b]; pairs with rows of fraction recip_id[b]. So we subtract rowCnt[ recip_id[b] ]. Good.
Now ensure that we have recip_id for each number. It is just the id of (q,p) for its (p,q). Since we inserted both, we can lookup.
Now we need to be careful about integer overflow: totalCount can be up to xy max 1e51e5 = 1e10, which exceeds 32-bit. Use long long.
Now check the while loop condition: while y >= 1 and totalCount - rowCnt[ recip[y] ] >= w. But is it safe to subtract rowCnt[ recip[y] ] before actually updating colCnt? Yes, because we are testing if after removal we would still have >= w. But note that colCnt[ id[y] ] includes the column y currently, and rowCnt[ recip[y] ] is the current count of rows that pair with it. So removal reduces totalCount by that amount. If condition holds, we perform removal.
But careful: The rowCnt[ recip[y] ] includes rows from 1..x. That's correct. However, there is an edge case: what if column y's fraction is such that its reciprocal fraction is the same as its own? (i.e., p = q). Then recip_id[y] = id[y]. Then rowCnt[ recip[y] ] = rowCnt[ id[y] ]. That's fine.
Also, if we remove column y, we decrement colCnt[ id[y] ]. That's necessary for future updates when adding rows later. But after removal, does totalCount remain consistent? Yes, we subtracted rowCnt[ recip[y] ] which accounts for lost pairs. And we also decremented colCnt. So after removal, totalCount is correct for rectangle (x, y-1).
Now, one more nuance: In the while loop, after we decrement y, the column that was at index y (old) is removed. Next iteration, we consider new y (previous y-1). We again compute condition using rowCnt[ recip[new y] ]. That's correct because colCnt now reflects columns 1..new y.
Now, initial state: colCnt includes columns 1..maxy. But note that columns are numbered 1..maxy. When we later remove columns, we always remove from the top? Actually we remove the highest index y, because we want the smallest y. That is correct because we want to shrink the prefix from the right end. This ensures that we keep the earliest columns. However, is it always optimal to remove the highest index? In terms of reducing y, we must remove columns from the end to maintain the property that colCnt corresponds to a prefix [1, y]. So removal of column y is the only way to reduce y by 1 while keeping prefix. So it's forced.
Now, consider the order of removal: we start with y = maxy, and after each row addition, we try to remove as many columns as possible. But note that after adding more rows, the required y may decrease further. Since we only ever decrease y, we never need to increase it. So the algorithm will find for each x the minimal y such that count(x, y) >= w, given that we start from the largest possible y and only reduce. This works because for larger x, the minimal y is <= previous minimal y.
But is it possible that after some row addition, the minimal y might need to be larger than current y? Since we have only decreased y, it could be that for a new x, the minimal y is actually larger than our current y (if earlier we decreased too much). But because minimal y is non-increasing with x, it cannot increase when x increases. So if we have the minimal y for previous x, it is >= minimal y for current x. So if we maintain y as the minimal y for the current x (or maybe not minimal but some y), and we only decrease, we won't overshoot. But we need to ensure that when we start the loop for x, we have y from previous iteration, which was minimal for previous x? Actually we maintain y as the minimal y for the previous x? Not exactly. After processing x-1, we have y that is minimal such that count(x-1, y) >= w? Let's see: At the end of iteration for x-1, we performed removals until totalCount - rowCnt[recip[y]] < w, meaning that for (x-1, y) totalCount >= w, but for (x-1, y-1) it would be < w. So y is minimal for x-1. For next x, we add a row, so count(x, y) >= count(x-1, y) >= w. So (x, y) is still valid. The minimal y for x could be <= current y. So we try to reduce further. So the algorithm will find the minimal y for each x, because we will keep reducing while possible. It never needs to increase because minimal y is non-increasing. So it's correct.
Now, we need to consider the case where at some x, after adding row, totalCount becomes < w? Could that happen? Since we start with y minimal for previous x, and we add a row, totalCount increases, so it will be >= w if previous count was >= w. But if previous count was < w, then after adding a row, it might become >= w or still < w. But note that if previous count was < w, then at previous iteration we did not have a valid rectangle, so we didn't attempt to reduce y further (y remained as before, perhaps maxy or some value). Actually if at x-1, totalCount (for that x-1 and current y) was < w, we didn't reduce y (since while condition requires totalCount>=w to try removal). So y stays at some value, which could be maxy or some lower value from previous reductions when it was valid earlier? But if earlier x was small and never achieved w, we wouldn't have reduced y because while condition only runs when totalCount>=w. So y may stay at maxy until we first achieve w. Then once we achieve w, we start reducing. So before achieving w, totalCount < w, and we won't record product. That's fine.
Now one more nuance: When we first achieve w at some x, we may have y = maxy (or some value). Then we will try to reduce y. That reduction may bring y down. Then for next x, we again try to reduce. So algorithm should find minimal y.
Thus overall complexity O(N) after building mapping.
Now we need to ensure that the mapping and gcd computations are correct.
Implementation steps:
Read maxx, maxy, w.
Let M = max(maxx, maxy).
Precompute rev for i=1..M. Since M ≤ 1e5, it's fine.
Define function rev:
int r=0, t=i;
while(t){ r = r*10 + t%10; t/=10; }
return r;
But note: rev(10)=1, rev(100)=1. That's fine.
Create vector<pair<int,int>> fractions(M+1) (p,q) after reduction.
Also compute reciprocals.
We'll use map<pair<int,int>, int> mp to assign ids later.
For i in 1..M:
r = rev(i)
g = gcd(i, r)
p = i / g
q = r / g
fractions[i] = {p,q}
Insert {p,q} and {q,p} into mp.
After loop, assign IDs: For each entry in mp (pair-> id) assign sequentially 0-index or 1-index.
Note: The order of insertion in map doesn't matter.
However, we need to store id for each i: we can get id = mp[{p,q}].
Also store recip_id[i] = mp[{q,p}].
Since we inserted both, this lookup will succeed.
Create arrays id(M+1), recip_id(M+1). Also rowCnt and colCnt arrays of size total_ids, initialized to 0.
We'll use vector rowCnt(cnt,0), colCnt(cnt,0). Use long long for counts but we can use int if small? rowCnt may go up to maxx (1e5), colCnt up to maxy (1e5). So int is fine but product for totalCount may be up to 1e10, so totalCount uses long long.
However, for rowCnt[recip_id[y]] we need to multiply rowCnt (int) and colCnt (int) but sum is long long. So rowCnt and colCnt can be int.
Pre-fill colCnt for b=1..maxy: colCnt[ id[b] ]++.
Initialize:
long long total = 0;
int y = maxy;
long long best = LLONG_MAX; int best_x=-1, best_y=-1;
// Note: we haven't added any rows yet.
Loop x from 1 to maxx:
// add row x
total += colCnt[ recip_id[x] ];
rowCnt[ id[x] ]++;
code
// shrink y
while (y > 0 && total - rowCnt[ recip_id[y] ] >= w) {
total -= rowCnt[ recip_id[y] ];
colCnt[ id[y] ]--;
y--;
}
if (total >= w) {
long long prod = 1LL * x * y;
if (prod < best) {
best = prod;
best_x = x;
best_y = y;
}
}
After loop, if best == LLONG_MAX, print -1; else print best_x best_y.
Edge Cases:
Need to ensure we don't access arrays out of bounds: id and recip_id defined for indices up to M. For y loop, we access recip_id[y] where y ranges 1..maxy. Since maxy ≤ M, it's fine.
While loop condition: total - rowCnt[ recip_id[y] ] >= w. But what if rowCnt[ recip_id[y] ] is huge? total - that may become negative? But if total >= w, and we attempt to remove column, we check if after removal still >= w. However, if total - rowCnt[ recip_id[y] ] may be negative? That would be < w, so condition fails. So it's fine.
We must ensure that when we remove column y, we also update colCnt accordingly. Also, after removal, we need to consider the new y. The while loop condition uses the new y after decrement.
What about the possibility that y becomes 0? The while loop condition checks y > 0. If y becomes 0, we exit. But rectangle with y=0 is invalid; we only consider product when total >= w and y >=1. However, after removal, y might become 0 if we removed all columns. In that case, total would be 0? Actually if y=0, then colCnt all zero, total should be 0. But if w>0, total >= w cannot hold. So we wouldn't have product with y=0. So we should not consider y=0. In while loop we check y>0 before attempting removal. So if y becomes 0, loop stops. But we might have removed last column and then total < w? Actually we only remove if after removal total >= w. So if after removal total still >= w, we remove and y becomes 0 only if after removal we still have w, but with no columns total=0, impossible unless w=0, but w>=1. So that won't happen. So y will stay >=1 if total >= w.
Potential off-by-one: Should we check while (y >= 1 && total - rowCnt[ recip_id[y] ] >= w) or while (y >= 1 && total - rowCnt[ recip_id[y] ] >= w) ? Yes. But note: The rectangle after removal is (x, y-1). So we need to ensure that after removal we still have at least w. So condition is total - loss >= w. Good.
Now test with examples.
We'll write a small test in mind for example 2.
Example 2: maxx=132, maxy=10, w=35 -> output 7 5.
We need to verify counts. But trust.
But we must be careful about integer division: rev may produce numbers up to? For i up to 1e5, rev(i) may be up to 99999? Actually maximum rev for numbers up to 1e5 is 99999 for 99999, or 100000? 100000 reversed is 1 (since leading zeros dropped) -> 1. So rev <= 99999.
Now confirm mapping of fractions: For each i, compute rev, gcd, reduced fraction. But note: rev could be zero? If i has trailing zeros, rev drops zeros: rev(10)=1, rev(100)=1, rev(1000)=1. So rev never zero because i>=1, so at least one non-zero digit? If i=10, rev=1. So fine.
Potential issue: For i like 1000, rev=1. So p=1000, q=1, gcd=1. That's fine.
Now ensure that for numbers up to M, we compute correctly.
Now consider the initial colCnt for b=1..maxy. Since maxy may be up to 1e5, it's fine.
Now complexity: O(M) for building fractions, O(M log M) for map insertion (since we insert up to 2M pairs, but each insertion O(log size) ~ log 1e5 ~ 17). So total ~ 2e5 * log 1e5 ~ fine.
Alternatively, we could use hashing for O(1) average.
Now test on example 4: 48 132 235 -> output 22 111. Let's try to think if algorithm yields that. Hard to manually compute.
Potential pitfalls: The mapping of fractions may have many distinct IDs, but arrays size up to maybe 2e5, fine.
Now we must confirm that the algorithm indeed finds minimal xy. Let's think about if there might be a scenario where the minimal product is not achieved by taking minimal y for each x. Since product is xy, for each x the minimal y that works gives the minimal product for that x. So scanning all x and taking min over them yields global minimum. But does the algorithm guarantee that for each x we get the minimal y? Let's prove:
At start of iteration for x, we have a state where y is minimal for x-1 (i.e., the smallest y such that count(x-1, y) >= w, or if count(x-1, maxy) < w then y = maxy? Actually if count(x-1, maxy) < w, then for x-1 there is no y that works; we cannot talk about