We need to parse the problem carefully.
We have C courses, numbered 1..C. Initially, N students have already applied for different courses before Monk and his friends. The i-th student (i from 1 to N) chooses the i-th course? Let's read: "The next line consists of N space separated integers Y[i] which denotes the IQ of the i^th student. Here, the i^th student chooses the i^th course." So initially, student 1 applies to course 1, student 2 to course 2, ..., student N to course N. So for courses 1..N, we have one student each, with given IQ Y[i]. For courses N+1 .. C, initially no students.
Now, we have P more students (Monk and his friends). They will choose courses one by one, in order (Monk first, then his friends). For each choice, they compute for each course i a value z = x * c, where:
- c is the number of students already enrolled in the course i (i.e., before this student chooses).
- x is the sum of IQ of the last two students who enrolled in that course. If a single student has applied for that course, then x = that student's IQ. If no student has enrolled, then x = 0.
Then they choose the course with minimum z. If tie, choose the course with minimum number.
After choosing, they enroll in that course (i.e., increase c by 1, and update the last two students' IQ list: presumably the new student's IQ becomes the most recent, and we keep track of the two most recent IQs for that course for future calculations). However, note that for the next student, the state changes.
We are given P IQs for the sequence of new students (Monk and friends) as X[1..P] (in order). We need to output for each new student the course number they applied for.
Constraints: C up to 100k, P up to 100k, so total operations O((C+P) log C) likely needed.
We need to maintain for each course:
- count (c) of students enrolled so far.
- maybe a queue of last two IQs? Actually we need to know the sum of IQ of the last two students (or the IQ if only one, or 0 if none). So we need to keep track of the two most recent IQs. Let's define:
- if count = 0: x = 0
- if count = 1: x = IQ of that single student
- if count >= 2: x = IQ_last + IQ_second_last (sum of two most recent enrollments). Note: order of enrollment matters, and we need to update when a new student joins: the new IQ becomes the new last, the previous last becomes second last (if there was at least one). So we can maintain a deque of length up to 2, or two variables.
Also, for each course, we need to compute z = x * c. Initially, for courses 1..N, count=1, x = Y[i] (since one student). For courses N+1..C, count=0, x=0, so z=0. Also for courses with count=0, z=0. But careful: if count=0, x=0, then z=0. So many courses may have z=0 initially. However, the tie-breaking rule says choose minimum z, and if equal choose minimum course number. So initially, if there are multiple courses with z=0 (all courses with no students, i.e., N+1..C), the minimum course number among those is N+1 (if N<C). But wait: courses 1..N have z = Y[i]*1 = Y[i] (positive since Y[i] >=1). So those have positive z. So the minimum z is 0 for all empty courses. Among those, the smallest course number is the smallest empty course number. Since courses are numbered 1..C, the empty courses are from N+1 to C, so the smallest empty is N+1 if N < C; but if N=C, then there are no empty courses initially, and min z would be among courses with count >=1. In the sample: C=5, N=4, so empty courses: course 5 only. So initial min z is 0 for course 5. That's why Monk picks course 5.
Then after Monk joins course 5, we update its state: count becomes 1, last IQ = Monk's IQ (9). x becomes that IQ (since count=1). So z for course 5 becomes 9 * 1 = 9. Now for other courses: course 1: count=1, x=2 => z=2; course 2: 18=8; course 3: 15=5; course 4: 1*1=1. So the next friend (IQ=10) will compute z: For each course, c is current count, x sum of last two IQs? Wait: For courses with count=1, x = that IQ; for course 5 now count=1, x=9 => z=9. For course 4, count=1, x=1 => z=1, which is minimum. So he picks course 4.
Then update course 4: count becomes 2, last two IQs: previously had student with IQ=1, now new IQ=10. So the two most recent: the last two are (1,10) in order? Actually last two are the most recent: after enrolling, the new student's IQ=10 becomes last; previous student (IQ=1) becomes second last. So x = 1+10 = 11. Count=2, so z = 11 * 2 = 22. But careful: For course 4, count now 2. So we have to recalc.
Continue.
Thus we need a data structure to quickly find the course with minimum z = x * c, with tie-breaking by minimum course number. After each assignment, we need to update that course's data and recompute its z.
Total courses up to 100k, and P up to 100k, so we could maintain a min-heap (priority queue) keyed by (z, course number). Initially compute z for all courses and push into heap. For each new student, we pop the top element (minimum z, min course number if tie) — but careful: After updates, the heap may contain outdated entries for courses whose z changed. So we need a way to manage updates. Standard approach: when we pop, we check if the entry matches the current state (i.e., if the z in the heap equals the current computed z for that course). If not, discard and pop again. Then assign the student to that course, update the course's state, compute new z, and push a new entry into the heap.
Complexities: O((C+P) log C) if each course gets updated O(1) times per assignment? Actually each assignment updates exactly one course, and we push one new entry. So total pushes = initial C + P (one per update). Each pop may also discard outdated entries. In worst case, each outdated entry is discarded once. Since each update creates one new entry, the total number of entries pushed is C + P. Each entry is popped at most once. So total heap operations O((C+P) log (C+P)) = O((C+P) log C). That's fine.
But we need to maintain per course: count, last two IQs, and current z for validation. Alternatively, we could also store current z in an array, and when pushing new entry, store that z. When popping, compare to current z for that course.
Now, we need to be careful about the definition of x: sum of IQ of the last two students who enrolled in that course. For count=0, x=0; for count=1, x = IQ of that single student; for count>=2, x = IQ of last two enrolled students (the two most recent). So after each enrollment, we need to update the last two. This is straightforward: maintain two variables: last1 (most recent), last2 (second most recent). Initially for count=0: undefined; for count=1: last1 = IQ of that student, last2 unused. When a new student with IQ iq enrolls:
- if count == 0: after enrollment, count=1, last1 = iq, last2 = none.
- else: we shift: new last2 = last1; new last1 = iq; count += 1.
But note that for x when count>=2, we use sum of last two: last1 + last2.
Thus after update, if new count == 1 => x = last1; else x = last1 + last2.
Now compute new z = x * count.
Edge cases: When count becomes 0? That can't happen because enrollments only increase. So count is non-decreasing.
Now we need to handle initial state: For i=1..N: count=1, last1 = Y[i]; no last2. So x = Y[i]; z = Y[i] * 1.
For i=N+1..C: count=0, x=0, z=0.
Now we process P students in order, each with IQ X[i].
For each student:
- Extract course with min (z, courseNumber). That's the chosen course.
- Output course number (store for output).
- Update that course's state: count++, update last1/last2, recompute x, compute new z.
- Push new (z, courseNumber) onto heap.
But there is nuance: The students themselves have IQ that influence the update, and they are the new enrollees. So we use the student's IQ for updating the course.
One more nuance: The condition says: "They will choose the course i (1 ≤ i ≤ C), for which the value of z is minimum. Here, z = x*c where c is the number of students already enrolled in the course i and x is the sum of IQ of the last two students who enrolled in that course." The wording: "already enrolled" implies c is the current count before the new student enrolls. That matches our usage. And x is the sum of IQ of the last two students already enrolled (i.e., before the new enrollment). So when computing z for the decision, we use the state before the new enrollment. So we pop the minimum based on current state, then enroll. Good.
Now we need to think about tie-breaking: if z equal, choose smallest course number. In our heap, we can store tuples (z, courseNumber). Since we want min z and min course number if tie, we can order by z then courseNumber ascending. In Python's heapq, it uses lexicographic order, so pushing (z, course) works fine: it will pop the smallest z, and if equal the smallest course.
Now confirm sample:
C=5, N=4, Y = [2,8,5,1] (courses 1-4). So initial:
1: count=1, last1=2, x=2, z=2
2: count=1, last1=8, z=8
3: count=1, last1=5, z=5
4: count=1, last1=1, z=1
5: count=0, x=0, z=0
Heap: (0,5),(2,1),(8,2),(5,3),(1,4). But heap order: (0,5) min; then (1,4); (2,1); (5,3); (8,2).
Monk IQ=9: pop (0,5) -> course 5. Update: course5 count 0->1, last1=9, x=9, count=1 -> new z = 9*1=9. Push (9,5).
Now heap: (1,4),(2,1),(5,3),(8,2),(9,5).
First friend IQ=10: pop (1,4) -> course 4. Check if current z for course4 is still 1? Yes, because we haven't changed it yet. So assign. Course4 before: count=1, last1=1. Update: count=2, last2 becomes 1, last1 becomes 10, so x = 1+10=11, count=2 -> new z = 22. Push (22,4).
Now heap: (2,1),(5,3),(8,2),(9,5),(22,4).
Second friend IQ=5: pop (2,1) -> course1. Update: course1 count 1->2, last1=2, last2 becomes 2? Wait course1 had last1=2 (only student). After adding IQ=5: last2=2, last1=5 => x = 7, count=2 => new z = 14. Push (14,1).
Heap: (5,3),(8,2),(9,5),(14,1),(22,4).
Third friend IQ=1: pop (5,3) -> course3. Update: course3 count 1->2, last1=5, last2=5? Actually course3 had last1=5. Add IQ=1: last2=5, last1=1 => x=6, count=2 => new z = 12. Push (12,3).
Now done. Output: 5 4 1 3. Matches sample.
So the algorithm works.
Now consider complexity and implementation details.
We need arrays of size C+1 (1-indexed) to store:
- count (int)
- last1 (int) - most recent IQ
- last2 (int) - second most recent IQ, maybe only used when count>=2.
- current_z (int) for validation.
Initialize:
- For i in 1..N: count[i] = 1; last1[i] = Y[i]; current_z[i] = Y[i] * 1.
- For i in N+1..C: count[i] = 0; last1[i] = 0 (or undefined); current_z[i] = 0.
Push all (current_z[i], i) into heap.
Then for each new student IQ:
- while True: pop (z, i) from heap; if z == current_z[i] (and maybe also check that the course exists? but we have that) then break; else discard (outdated).
- record i as chosen course for this student.
- // Update state:
- iq = student IQ.
- c = count[i]; // current count before enrollment
- if c == 0:
new_count = 1
new_last1 = iq
new_last2 = None? Actually we only need to maintain last1, last2 for future. Since new_count=1, x will be iq.
// update variables: count[i] = 1; last1[i] = iq; last2[i] remains whatever (maybe set to 0 irrelevant)
- else if c == 1:
// currently last1 holds the only IQ. After adding, we have two. So new_last2 = last1[i]; new_last1 = iq; new_count = 2.
// then x = last1 + last2 = iq + last1_old.
- else: // c >= 2
// shift: new_last2 = last1[i]; new_last1 = iq; new_count = c+1.
// x = iq + last1_old (since last1_old is previous most recent)
- In all cases, after update we can compute new x:
if new_count == 0: x=0 (should not occur)
elif new_count == 1: x = new_last1
else: x = new_last1 + new_last2 (where new_last2 is second most recent, which is old last1 if c>=1, etc.)
- new_z = x * new_count.
- Update count[i], last1[i], last2[i], current_z[i] = new_z.
- Push (new_z, i) onto heap.
But we need to handle last2 properly. Let's store last2 as integer, maybe initially 0. For count<2, last2 is irrelevant; we can set it to 0. For update: if c >= 1, then new_last2 = last1[i]; else if c==0, there is no last1, so new_last2 = 0? Actually after adding to empty course, we have only one student, so we don't have a second last. So we should keep last2 as something (maybe 0) but we will not use it until count>=2. However, for simplicity, we can always update last2 = last1[i] if c >= 1; if c == 0, set last2 = 0 (or ignore). Because when count becomes 2, last2 will be set from the previous last1 (which was the only student). That is correct: after adding to empty, count becomes 1, and last2 is not used. But if later we add a second student to that course, we will need the previous last1 (the one added when count went from 0 to 1) as last2. So we should store last1 after each update, and last2 only when needed. Actually we can compute x on the fly based on count: if count == 0: x=0; count ==1: x=last1; count >=2: x = last1 + last2. So we need to maintain last2 when count>=2. And after adding a student, if the old count was >=1, we set new_last2 = old last1. That works regardless of old count (1 or more). So algorithm for update:
Given old_count, old_last1, old_last2 (old_last2 may be irrelevant if old_count<2, but we have it stored perhaps as 0). Then:
new_count = old_count + 1
if old_count == 0:
new_last1 = iq
new_last2 = 0 (or keep old_last2? doesn't matter)
else:
new_last2 = old_last1
new_last1 = iq
For old_count >=1, new_last2 becomes the previous last1, which is correct for when new_count >=2.
Now compute x:
if new_count == 0: x=0
elif new_count == 1: x = new_last1
else: x = new_last1 + new_last2
Then new_z = x * new_count
Update fields:
count[i] = new_count
last1[i] = new_last1
last2[i] = new_last2 (store always, maybe for future)
current_z[i] = new_z
Push.
Note: For old_count>=2, old_last2 is not used for x after update, because we only need the sum of the two most recent, which are new_last1 and new_last2 (which is old_last1). The previous old_last2 becomes irrelevant. So we don't need to keep a queue longer than 2; we just need last1 and last2. So updating as above works.
Now one nuance: When old_count == 0, we set new_last2 = 0. Then if later we add another student (making count=2), new_last2 will be set to the previous last1 (the first student) properly. That works.
Now we need to be careful about integer overflow? Values: IQ up to 100k. x can be sum of two IQs, up to 200k. c can be up to (N+P) per course. In worst case, all P+N students might enroll in a single course if its z remains minimal? But with the multiplication, as c grows, z likely becomes large, so distribution may spread. But theoretically, worst-case c could be up to N+P (≤ 200k). So x*c could be up to 200k * 200k = 4e10, which fits in 64-bit integer (Python int unlimited anyway). So fine.
Now we need to ensure that the heap always contains the current minimum. As we push new entries, we may have many outdated ones. The validation approach works.
Now the problem: Input format: first line: C P N. Next line: N integers Y[1..N]. Next line: P integers X[1..P].
We need to output P integers: courses chosen.
Edge Cases:
-
N = 0. Then no students initially. So all C courses have count=0, x=0, z=0. So the first student will choose course 1 (since min z=0 and tie break smallest course number). After enrolling, course1 count=1, x=IQ of student, z=IQ. Next student may again find other courses with z=0 (courses 2..C) so they'll pick course2, etc. So essentially they fill courses in order. But if multiple have z=0, the smallest course number is chosen. So it's like a round-robin? Actually until all courses have at least 1 student, they will fill from 1 upward because among zeros, the smallest index wins. After all courses have at least one student, then they'll start picking based on computed z.
-
N = C. No empty courses initially. So the minimum z will be among those with Y[i] maybe. The algorithm works.
-
Some courses may have same z over time, and tie-breaking will pick smallest course number.
Now we need to be careful about handling the heap with outdated entries. When we pop, we compare z from heap to current_z[course] which we maintain. However, what about if a course has been updated multiple times? The heap may contain multiple entries for that course. The current_z always reflects the latest state. So any popped entry that does not match is outdated and we skip.
Implementation steps in Python:
-
Read C, P, N.
-
Read list Y of length N (maybe if N=0, the line may be empty? But constraints say N≥1? Actually constraints: 1 ≤ N ≤ C, so N>=1, so always at least one initial student? Wait: "1 ≤ N ≤ C". So N can be 1? Actually min is 1. So N>=1. So there will always be at least one Y. So N>=1. So we can safely read Y list. However, if N could be 0 maybe not. But given constraints, N>=1. So no need to handle N=0, but it's easy: if N==0, the next line might be empty, but better to handle general. But we'll assume as per constraints N>=1.
-
Read list X of length P.
-
Initialize arrays of size C+1 (index from 1):
count = [0](C+1)
last1 = [0](C+1)
last2 = [0](C+1)
cur_z = [0](C+1)
-
For i in range(1, N+1):
count[i] = 1
last1[i] = Y[i-1] (since Y list 0-indexed)
cur_z[i] = Y[i-1] * 1
-
For i in range(N+1, C+1):
count[i] = 0
cur_z[i] = 0
last1,last2 remain 0
-
Initialize heap = []
-
For i in range(1, C+1):
heapq.heappush(heap, (cur_z[i], i))
-
Initialize result list.
-
For each iq in X:
while True:
z, cid = heapq.heappop(heap)
if z == cur_z[cid]:
break
# else continue
cid is the chosen course
result.append(cid)
update course cid with iq
old_count = count[cid]
old_last1 = last1[cid]
old_last2 not needed except maybe for debug
compute new state
new_count = old_count + 1
if old_count == 0:
new_last1 = iq
new_last2 = 0
else:
new_last2 = old_last1
new_last1 = iq
compute x and new_z
if new_count == 0:
x = 0
elif new_count == 1:
x = new_last1
else:
x = new_last1 + new_last2
new_z = x * new_count
update arrays
count[cid] = new_count
last1[cid] = new_last1
last2[cid] = new_last2
cur_z[cid] = new_z
push new entry
heapq.heappush(heap, (new_z, cid))
-
After loop, print result as space separated.
Test with sample.
Now verify with some other scenarios.
Edge case: Suppose N=1, C=3, Y=[100], so courses: 1: count=1, z=100; 2:0;3:0. P=2, X=[50,60].
Initial heap: (0,2),(0,3),(100,1) maybe order (0,2),(0,3),(100,1). First student: pop (0,2) -> valid, choose course2. Update: course2 count 0->1, last1=50, z=50. Push (50,2). heap now: (0,3),(50,2),(100,1). Second student: pop (0,3) -> valid, choose course3. Update: course3 count 0->1, last1=60, z=60. Push (60,3). Output: 2 3. That seems correct: they pick smallest empty courses first because z=0 minimal.
But what about if there are many empty courses, they would pick the smallest index. So it's consistent.
Now consider scenario where some courses have same z non-zero. Eg, after some enrollments. That's fine.
Now potential pitfalls:
-
The heap may contain entries for courses with outdated z. The validation uses equality. Since we update cur_z to new_z, the previous z may be different. This works.
-
But what about when z is large and same as new_z? Could cause a false positive? Suppose a course gets updated and new_z coincidentally equals the old z from a previous outdated entry? That is possible: For a course, we push new entry with new_z. Old entries remain. When we later pop an old entry, we compare its z to current cur_z. If cur_z equals that old z, then we might mistakenly accept an outdated entry if the current state happens to have the same z value as an earlier state. Is that possible? Yes, it's possible that after some updates, the z value returns to a previously seen value. However, that old entry would be for the same course, but it's outdated because it represents a different state (different count and maybe different x). But if the cur_z equals that z, then the old entry would be considered valid even though it's not the most recent? But note: the old entry corresponds to a previous state. But if cur_z now equals that old z, then the course currently has that z value. The old entry is still an accurate representation of the course's current z? Actually no, because the entry also contains the course number, but the heap entry doesn't include any other info. When we pop (z, cid) and we check if z == cur_z[cid], and if they are equal, we accept it. But if an outdated entry (from a previous state) has the same z as the current cur_z, then the check passes, and we would treat it as the current minimum. However, is that correct? The outdated entry's z value matches the current z, so it is still a correct representation of the current priority? Actually, the outdated entry's value is equal to the current z, but it doesn't carry any extra state; the priority is solely based on the numeric value and the course number. So if the numeric value matches the current one, then using that entry to pick the course is fine: it yields the same tuple (z, cid) as if we had pushed a new entry. Since the priority queue only cares about the ordering key (z, cid), the fact that the entry is old doesn't affect correctness, as long as the key is correct. The only danger is if the outdated entry corresponds to a state where the z was the same but the course number? That's the same. So it seems safe: if z equals cur_z, the current state has that z, and the heap entry's key matches the current key. So it's valid to use that entry to select the course. There's no additional information (like count) needed. So the simple equality check suffices to ensure that the popped entry reflects the current state (or at least that the current state's z is the same, so it's not outdated). Because if the entry's z differs from cur_z, it means the course was updated and cur_z changed; the entry is outdated and should be discarded. But if the entry's z equals cur_z, it could be from the current state or from a previous state that coincidentally had same z. But if it's from a previous state, then the course must have been updated later to a different state, and then updated again to a state where z returns to that same value. In that case, the outdated entry would still have the same key as the current one. However, there might also be a newer entry for the same course with the same key (since we push after each update). That's okay: multiple entries with same key are allowed. When we pop, we might get either the outdated or the newer one. If we pop an outdated one but it passes the equality test (since cur_z equals that z), we use it. That is fine because the course's current key is exactly that; selecting that course now is correct. And after we update the course, we will push a new entry with the new z. The remaining outdated entries (if any) will fail the equality test later because cur_z will have changed. So no harm.
But is there a scenario where an outdated entry with the same z is popped, but we still have an even more recent update that we haven't accounted for? Actually if we have an outdated entry that has same z as current, it means that after that outdated entry was generated, the course was updated at least once (maybe multiple times) and arrived at a state with the same z. At the time we pop, cur_z is that value. So it's current. So it's fine.
Thus the equality check is sufficient.
Now, we must be careful that we maintain cur_z correctly. So algorithm is correct.
Now we should also consider if the initial heap might contain duplicate entries for the same course? Initially we push one per course. So only one per course. After each update, we push one more, so there could be multiple per course. That's okay.
Now memory: heap size up to C + P, which is <= 200k, fine.
Now confirm that we handle the case where N = C and there are no empty courses. Then all courses have some positive z. The algorithm still works.
Now consider a scenario: Some courses may have count=0 but x=0 => z=0. So many courses have z=0 initially. The heap will have multiple entries with z=0. The smallest course number among them will be popped first. So they will fill the empty courses in increasing order. That matches the sample explanation: Monk picked course 5 because it was the only empty. If there were multiple empties, he'd pick the smallest.
Now after all empties are filled, they might still have courses with low z. But note that if all courses have at least one student, then further selections will be based on computed z. But note: When count=1, x = IQ of that student, z = IQ. So essentially initially after all courses have at least one, the next candidate will pick the course with smallest IQ among those single-student courses. After that, the course becomes count=2, and x becomes sum of the two IQs, z = (sum)*2. This could become large, so the next smallest might be some other course with a small IQ. So the process could be like: pick the course with smallest current single-student IQ first, etc.
Now there is also the possibility that some course may have count>2, but still have a small z if x is small? For example, if a course has many students but the last two IQs are very small, the product may be small. So we must handle general.
Now implementation details:
-
Use 0-index vs 1-index. We'll use 0-index for Python lists but then course numbers 1..C. So we can allocate arrays of size C+1 and ignore index 0.
-
Input reading: use sys.stdin.read() for speed? Since constraints up to 100k, it's okay to use sys.stdin.readline.
-
Output: print(' '.join(map(str, result)))
Now test with custom example:
Example: C=3, P=3, N=1, Y=[5], X=[1,2,3].
Initial:
1: c=1, last1=5, z=5
2: c=0, z=0
3: c=0, z=0
Heap: (0,2),(0,3),(5,1) order: (0,2),(0,3),(5,1)
Student1 IQ=1: pop (0,2) -> valid, choose 2. Update: c2=1, last1=1, z=1. Push (1,2). Heap: (0,3),(1,2),(5,1)
Student2 IQ=2: pop (0,3) -> valid, choose 3. Update: c3=1, last1=2, z=2. Push (2,3). Heap: (1,2),(2,3),(5,1)
Student3 IQ=3: pop (1,2) -> valid (cur_z[2]=1), choose 2. Update: c2 now 2 (old count=1, last1=1). new_last2=1, new_last1=3 -> x=4, count=2 -> z=8. Push (8,2). Heap: (2,3),(5,1),(8,2)
Now output: 2 3 2. Is that correct? Let's compute manually: after student1 picks course2, student2 picks the remaining empty course3, then student3 sees: course1 z=5, course2 z=1, course3 z=2 -> min is 1 (course2), picks course2. Yes.
Now test with N=C=2, Y=[100,1], X=[10,20]. Initial:
1: c=1, z=100; 2: c=1, z=1. Heap: (1,2),(100,1). Student1 IQ=10: pop (1,2) -> choose 2. Update: course2 count=2, old last1=1, new_last2=1, new_last1=10 -> x=11, count=2 -> z=22. Push (22,2). Heap: (100,1),(22,2). Student2 IQ=20: pop (100,1) -> choose 1. Update: course1 count=2, old last1=100, new_last2=100, new_last1=20 -> x=120, count=2 -> z=240. Output: 2 1. OK.
Now test with ties: Suppose C=2, N=0 (but N>=1 per constraints, but let's test general) P=2, X=[5,5]. But N can't be 0, but we can adjust: C=2, N=2, Y=[0? but IQ>=1]. Actually to simulate ties, consider C=3, N=3, Y=[2,2,2], X=[10,10]. All initial z=2. Ties? For courses 1,2,3 all z=2. According to tie-breaking, min course number is 1. So first student picks 1. Then update course1: c=2, last1=2, last2=2? Actually initial last1=2, count=1. After adding IQ=10: new_last2=2, new_last1=10 -> x=12, c=2 -> z=24. So new z for course1 is 24. Remaining courses: 2: z=2, 3: z=2. Next student picks min among (24,2,2) -> 2 (course2 if tie? Actually both 2, so min course number 2). So output: 1 2. Our algorithm: initial heap: (2,1),(2,2),(2,3) order: (2,1),(2,2),(2,3). Student1: pop (2,1) -> valid. Choose 1. Update to z=24, push (24,1). Heap now: (2,2),(2,3),(24,1). Student2: pop (2,2) -> valid. Choose 2. Works.
Now, what about after updates causing multiple entries with same z? That's fine.
Now, consider the possibility of integer division or overflow? Not.
Now, we need to be mindful of the fact that the computation of x uses sum of the last two enrolled students. In the case count=1, x is that student's IQ. When a new student enrolls, we should use the sum of the last two (the existing one and the new one). That matches our update: after adding, if new_count >=2, x = new_last1 + new_last2, where new_last2 is the previous last1. Good.
Now, check a scenario where count >= 2 and we add a third student. Then old_count = 2, old_last1 = most recent, old_last2 = second most recent. After adding new IQ, new_last2 = old_last1, new_last1 = iq. The old_last2 is discarded. So x becomes iq + old_last1. That's correct: sum of last two (new student and previous most recent). So we don't need to keep old_last2 beyond that.
Now, verify with an example: Course initially has students with IQs: 10 (first), 20 (second), so count=2, last1=20, last2=10, x=30, z=60. Add third student IQ=30. old_count=2, old_last1=20, old_last2=10 (but we don't use old_last2). new_last2=20, new_last1=30 -> x=50, count=3 -> z=150. That matches: last two are 20 and 30 sum=50; product=150. So correct.
Now algorithm seems solid.
Now we need to consider performance: For each student, we may have to pop multiple outdated entries. In worst-case, there could be many outdated entries. However, each outdated entry is popped once and then discarded. Since total pushes = C + P, total pops <= pushes. So overall O((C+P) log (C+P)). For C,P up to 100k each, that's fine.
Now, implement.
But wait: The problem statement: "Monk and his P-1 friends recently joined a college." It says "P denotes Monk and his friends". So there are P persons including Monk. So there are P new students. In sample, P=4, so Monk + 3 friends, total 4. The input line has P integers X[i] which denotes the IQ of Monk and his friends. The order is given: "Monk will choose his course first followed by his friends." So we process X in that order.
Now output: print P space separated integers.
Edge Cases: In the initial state, courses may have count > 1? No, initial N students each applied to distinct courses i=1..N, so each has exactly 1 student. So count=1 for courses 1..N. Good.
Now think about the potential for large C and small N. The heap will contain many entries with z=0 (empty courses). We need to efficiently pop the smallest course number among them. Since we store (0, i) and heap orders by tuple (z, i), the smallest i among those with z=0 will be at top because all z are equal. So that works. However, we push many (0,i) for i=N+1..C. That's fine.
Now, after some enrollments, some courses may have count=1 and z = IQ. This may be less than 0? No, IQ >=1, so z>=1. So after all empty courses are taken, the next smallest z will be among the smallest IQ courses.
Now we might consider that after an empty course is taken, its z becomes positive (IQ). That could be larger than some other empty courses still with z=0. So the algorithm will continue to pick empties first. So essentially, the first min(C - N, P) new students will take the empty courses in increasing order. If P > (C-N), then after filling all empties, the remaining students will choose among courses based on computed z.
Now implement.
Potential issues: The sample input has newline characters. We'll read using sys.stdin.read().split().
We can also read line by line. But careful: Input lines may be large; using sys.stdin.buffer.read() is safe.
We'll parse:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
C = int(next(it))
P = int(next(it))
N = int(next(it))
Y = [int(next(it)) for _ in range(N)]
X = [int(next(it)) for _ in range(P)]
# Initialize arrays
count = [0] * (C+1)
last1 = [0] * (C+1)
last2 = [0] * (C+1)
cur_z = [0] * (C+1)
for i in range(1, N+1):
count[i] = 1
last1[i] = Y[i-1]
cur_z[i] = Y[i-1] # *1
for i in range(N+1, C+1):
# already zeros
pass
import heapq
heap = []
for i in range(1, C+1):
heapq.heappush(heap, (cur_z[i], i))
result = []
for iq in X:
while True:
z, cid = heapq.heappop(heap)
if z == cur_z[cid]:
break
result.append(cid)
old_count = count[cid]
old_last1 = last1[cid]
new_count = old_count + 1
if old_count == 0:
new_last1 = iq
new_last2 = 0
else:
new_last2 = old_last1
new_last1 = iq
if new_count == 0:
x = 0
elif new_count == 1:
x = new_last1
else:
x = new_last1 + new_last2
new_z = x * new_count
count[cid] = new_count
last1[cid] = new_last1
last2[cid] = new_last2
cur_z[cid] = new_z
heapq.heappush(heap, (new_z, cid))
sys.stdout.write(' '.join(map(str, result)))
if name == "main":
main()
Check sample.
Now, consider if N could be 0? The constraints say N≥1, so we are safe. But if we want robust code, we could handle N=0: then Y list reading would be for 0 elements, which we can handle by reading the next line? But our parsing method using .split() will just skip that line? Actually if N=0, the second line would contain nothing? The problem statement may still provide a line with nothing? Usually there would be an empty line or a line with spaces? To be safe, we can handle N=0 by not reading Y. Our code uses for _ in range(N): if N=0, it's fine, we don't read any Y. Then we need to ensure that we don't mistakenly treat that as missing. But constraints say N≥1, so we ignore. But I'll note that perhaps they might test N=0? Let's double-check constraints: "1 ≤ N ≤ C". So indeed N >=1. So fine.
Now about reading: The input format: first line: C P N. The next line: N integers Y[i]. The next line: P integers X[i]. So if N=0, there might be an empty line, but we will still try to read P integers from the next tokens. In our .split() approach, if N=0, after reading the first three numbers, the next tokens will be the P numbers for X. So Y list will be empty. That's fine. So the code works even if N=0? Let's test: Suppose C=3,P=2,N=0, then data: "3 2 0\n\n9 10\n"? Actually second line maybe empty or omitted. The tokens would be: ["3","2","0","9","10"]. Then Y = [] (since range(0) does nothing), X = [9,10] (since P=2). That works. However, initializing for i=1..N (none) is fine. Then for i in range(N+1, C+1) = range(1,4) would initialize? But wait, we didn't set count for i=1..C? In our code, we have two loops: for i in 1..N: set count=1 etc. For i in N+1..C: we do pass (since we didn't set anything, they remain 0 from initialization). But we also need to set cur_z for those courses? In the first loop for i=1..N, we set cur_z. For i>N, we rely on initial zero values from array creation. That's correct: count[i]=0, cur_z[i]=0. So for N=0, all i from 1 to C remain 0, which is correct. So the code works for N=0 as well. Good. But the constraints say N>=1, but it's okay.
Now, we push all (cur_z[i], i) for i=1..C. So for N=0, all are (0,i). That's fine.
Now, potential bug: In the update for old_count == 0, we set new_last2 = 0. That's fine. But what about when old_count >= 1, we set new_last2 = old_last1. However, if old_count == 1, old_last1 is the only IQ. That's correct. If old_count >= 2, old_last1 is the most recent, and we discard the old_last2, which is correct. But we also overwrite last2 with new_last2, which is old_last1. That's correct; we don't need to keep the old_last2. So it's fine.
Now, we also set last2 = new_last2 always. So after update, last2 is either 0 (if old_count==0) or old_last1.
Now, after multiple updates, last2 will always be the previous last1 (the student just before the latest). So it's correct.
Now, about x calculation: For new_count == 1, we used x = new_last1. That's correct because only one student. For new_count >=2, we used x = new_last1 + new_last2. That's correct because we have at least two students. But note: What about the case new_count == 2? Then we have new_last2 = old_last1 (the first student) and new_last1 = new student. So x = new_last1 + new_last2 = sum of the two students. Good.
Now, potential overflow: Not.
Now, let's test with a bigger random case to verify logic. We can test manually with small C and P using brute force simulation? But not needed.
Now, think about tie-breaking: Since we use (z, i) as tuple, Python's heap orders by first element then second. So the min course number among equal z will come out because (z, i1) < (z, i2) if i1 < i2. That's correct.
Now, is there any nuance about when z is computed? For courses with no students, x=0, c=0, so z=0. That's fine. But wait: the definition says: "If no student has enrolled for that course, then value of x will be 0." So x=0. And c = number of students already enrolled = 0, so z=0. So that's correct.
Now, for courses with one student: x = that student's IQ, c = 1, z = IQ.
Now, for courses with two or more: x = sum of last two, c = current count.
Now, note: The count c includes the students already enrolled; after we assign a new student, c increases. So z can increase significantly.
Now, is there any possibility that the heap's top entry is outdated and we keep popping forever? No, because at least one entry is current (the one we just pushed for the updated course). So eventually we will find a valid entry.
Now, time complexity: In worst-case, we might have many outdated entries before we find the valid one. But total pops is bounded.
Now, let's double-check memory: arrays size C+1 up to 100001, fine.
Now, output formatting: space separated and newline? We used sys.stdout.write(' '.join(...)). That does not add newline. Typically printing with newline is fine, but not necessary. We can add newline.
Now, test sample:
Input:
5 4 4
2 8 5 1
9 10 5 1
Our code output: "5 4 1 3" (without newline maybe). That matches.
Now, think about potential pitfalls with reading input: The input may have trailing spaces, but .split() handles.
Now, consider if P=0? Not allowed? P >= 1? Constraint: 1 ≤ P ≤ 100000, so P>=1, so at least Monk.
Now, everything seems fine.
Now, additional verification with a scenario where after many updates, a course's x may become 0? Not possible because IQs >=1, so x>0 if count>=1. If count=0, x=0. So not a problem.
Now, confirm that our update logic for x uses new_last1 and new_last2 correctly when new_count==2. For example, when old_count=1, old_last1=5, iq=3. Then new_count=2, new_last2=5, new_last1=3 => x=8. Good.
Now, is there any case where we need to consider that the last two students are the two most recent, but after a new enrollment, the previous "last two" concept shifts. That's covered.
Now, one more nuance: When we compute x for the decision (before enrollment), we use the last two students already enrolled. That's what we have in our state before enrollment. So our heap uses that z. Good.
Now, think about if we need to handle large number of courses and many queries efficiently. Python heap operations are O(log n). With up to 200k elements, it's fine.
Now, potential optimization: Since many courses start with z=0, we could directly assign to the smallest empty course without using heap? But it's simpler to use heap, and it's efficient enough.
Now, check for edge case: C=100000, P=100000, N=100000 (so all courses have one student initially). Then initial heap contains 100k entries with various z. Each student will pop the min and update one course, push new. So 200k heap ops, each O(log 100k) ~ 17, total ~3.4 million ops, fine.
Now, confirm that we correctly handle situation where N=0, C large, P large. Then initial heap contains C entries (0,i). The first pop will be (0,1). After that, we update course1: count=1, z=iq1. push (iq1,1). Then next student: heap contains (0,2), (0,3), ... (0,C), (iq1,1). The min is (0,2) (since 0 < iq1). So they will fill courses in order. So after C students, all courses have one student. Then subsequent students will choose among those based on iq. So it's fine.
Now, but we need to consider: In the heap, we have many (0,i) entries. After we fill a course, we push a positive z. But the heap still contains the original (0,i) entry for that course? Wait, originally we pushed (0,i) for each course i. Then when we update course i, we push a new (z,i). But the old (0,i) remains in the heap. Later when we pop that old (0,i), we will compare its z (0) to current cur_z[i] (which is positive). They differ, so we discard it. So after we've filled all courses, we will have exactly one outdated (0,i) for each course still in the heap. As we pop for new students, we may need to discard up to C outdated entries before we get to a valid one. That could happen if after filling all courses, the next student will have to discard all those outdated zeros to get to the smallest positive z. In worst case, if we have many outdated entries, we might pop O(C) outdated ones at once. But note that each outdated entry is discarded only once overall. Since there are C outdated entries (the initial ones), and we will eventually discard them all as we process future students. The total number of pops including discards is O(C+P). So the overall complexity remains O((C+P) log (C+P)). However, the worst-case per operation could be large if we discard many at once. But total over all operations, each outdated entry is popped once. So even if a particular operation discards many (like up to C), it's still O(C log C) total for discarding all of them. Since C ≤ 100k, that's acceptable. In practice, the heap will contain many entries, but discarding them one by one is fine.
Nevertheless, we can mitigate by not pushing initial entries for courses with z=0? Or we can push them and rely on the process. It's acceptable.
But is there a more efficient way? Another approach: Use a balanced BST or something. But heap is fine.
Now, potential improvement: Since we always want min (z, i), we could use a priority queue that supports decrease-key, but Python doesn't have it. So the lazy update is fine.
Now, edge case: When updating a course, the new_z might be zero? Only possible if new_count == 0 or x == 0. new_count >=1. If new_count == 1, x = new_last1 which is iq (>=1) => new_z >=1. If new_count >=2, x >= (new_last1+new_last2) >= 1+1=2 => new_z >= 2 * 2 = 4? Actually could be 2*1? Wait count=2, x could be 1+1=2 => new_z=4. So new_z never zero after enrollment. So outdated entries of zero will be discarded eventually.
Now, consider the case where initial N=C and some Y[i] could be 0? But constraints: Y[i] >= 1, so no zero.
Now, let's produce final answer.
We'll write the solution in Python with above code.
Before finalizing, let's double-check with a few more scenarios.
Scenario 1: C=1, N=1, Y=[5], P=2, X=[10,20].
Initial: course1: count=1, z=5. Heap: (5,1). Student1: pop (5,1) -> choose 1. Update: old_count=1, old_last1=5, new_count=2, new_last2=5, new_last1=10 -> x=15, new_z=30. Push (30,1). Student2: heap now (30,1). Pop (30,1) -> valid. Choose 1. Update: old_count=2, old_last1=10, old_last2=5, new_count=3, new_last2=10, new_last1=20 -> x=30, new_z=90. Output: 1 1. That matches: only course, so they all pick it.
Scenario 2: C=3, N=1, Y=[100], P=3, X=[1,2,3]. Initially: course1: z=100, course2:0, course3:0. Heap: (0,2),(0,3),(100,1). First: picks 2 (z=0). Update: course2 z=1. Second: heap (0,3),(1,2),(100,1) -> picks 3 (z=0). Update: course3 z=2. Third: heap (1,2),(2,3),(100,1) -> picks 2 (z=1). Update: course2 becomes count=2, last two: 1 and 2? Actually course2 had first student IQ=1, now second IQ=3? Wait third student IQ=3 assigned to course2. So after update: count=2, last1=3, last2=1 -> x=4, new_z=8. Output: 2 3 2. That matches earlier.
Now, test tie-breaking with z equal but multiple entries. Example: C=4, N=4, Y=[3,3,3,3], P=2, X=[4,5]. All initial z=3. First picks course1 (tie smallest). Update: course1 count=2, last1=3 (first), actually old_last1=3, new student IQ=4 => new_last2=3, new_last1=4 => x=7, count=2 -> z=14. Heap now: (3,2),(3,3),(3,4),(14,1). Second picks course2 (z=3). Output: 1 2. Fine.
Now, consider a case where after some updates, the current minimum might be from an outdated entry that has same z as current, but we also have a newer entry with same z. That's fine.
Now, confirm that we treat the sum of last two correctly when count=1 becomes 2. Our code sets new_last2 = old_last1, new_last1 = iq. That's correct.
Now, ensure we handle large inputs efficiently. Using sys.stdin.buffer.read() and heapq should be fine.
Now, we need to output as space separated.
Now, before final answer, consider if there is any alternative interpretation: Could it be that the "last two students" includes the new student? The phrase: "x is the sum of IQ of the last two students who enrolled in that course." When deciding which course to choose, they consider currently enrolled students, so x is based on the existing last two. That matches our reading. Some might misinterpret that after enrollment, we use the last two (including the new student) for future decisions. Yes, that's what we do.
Now, final code.
But we must consider one more nuance: The initial N students applied for different courses: i-th student chooses i-th course. So they are already enrolled. So we have that.
Now, the problem might be from HackerEarth or similar, typical priority queue problem.
Now, let's produce final answer.
But wait, there's a subtlety: In the problem statement, it says: "They will choose the course i (1 ≤ i ≤ C), for which the value of z is minimum. Here, z = x*c where c is the number of students already enrolled in the course i and x is the sum of IQ of the last two students who enrolled in that course." It does not explicitly say that if only one student has enrolled, x = that student's IQ. But they state: "If a single student has applied for a course, then the value of x will be that student's IQ. If no student has enrolled for that course, then value of x will be 0." So that's clear.
Now, also "the last two students who enrolled in that course" implies we need to know the order of enrollment. Our update correctly maintains order.
Now, potential edge: When a course has exactly one student, last two? There is only one, so x = that IQ. That's fine.
Now, are there any other constraints? The number of courses C is up to 100k, so using arrays is okay.
Now, one more test: Suppose a course initially empty, then many enrollments. Our update sets last2 accordingly.
Now, test with multiple enrollments to same course to ensure x sum is correct: Let's simulate manually: Start empty.
Enroll A (IQ=10): count=1, last1=10, last2=0, x=10, z=10.
Enroll B (IQ=20): old_count=1, old_last1=10 => new_last2=10, new_last1=20, count=2 => x=30, z=60.
Enroll C (IQ=5): old_count=2, old_last1=20 => new_last2=20, new_last1=5, count=3 => x=25, z=75.
So the last two are 20 and 5, sum=25. That matches.
Our code: after A: count=1, last1=10, last2=0 (since old_count=0 set last2=0). After B: old_count=1, old_last1=10 => new_last2=10, new_last1=20 => count=2 => x = 20+10=30 => z=60. After C: old_count=2, old_last1=20 => new_last2=20, new_last1=5 => count=3 => x=25 => z=75. So correct.
Now, verify that after first enrollment into empty, last2=0. That's fine because it's not used for x until count>=2.
Now, we should ensure that we use ints for everything.
Now, final answer.
But before we finalize, we need to double-check the condition: "z = x*c where c is the number of students already enrolled in the course i and x is the sum of IQ of the last two students who enrolled in that course." Is it possible that c could be zero? Then x=0, so z=0. So that's consistent.
Now, consider that if a course has one student, x is that student's IQ, c=1 -> z=IQ. For a course with two students, x=sum of both IQs, c=2 -> z = 2sum. For three students, x=sum of last two, c=3 -> z = 3sum. That's fine.
Now, is there any trick with "last two" meaning the two most recent among all students ever enrolled, which includes possibly the same student if only one? Already covered.
Now, ensure we output course numbers in the order of Monk and his friends. The X array is in order, so we process in that order.
Now, done.
Now, potential pitfalls: The problem statement says: "If the value of z is same for two courses, then they will choose the course with the minimum course number." So if multiple courses have the same minimum z, choose the smallest course number. That's exactly what we do.
Now, we should test with a case where after some updates, the minimal z is not unique.
Example: C=3, N=3, Y=[2,2,2], P=3, X=[1,1,1]. Initially all z=2. First picks 1, updates to maybe? After first: course1 count=2, last1=2, last2=2? Actually initial last1=2, then add IQ=1 => new_last2=2, new_last1=1 => x=3, count=2 => z=6. So after first, courses: 1:z=6, 2:2, 3:2. Second picks min: between 2 (course2) and 2 (course3) pick course2. Update course2: similar to course1, becomes z=6. Third picks min: now course3:2, so picks course3. So output: 1 2 3. Our algorithm: initial heap (2,1),(2,2),(2,3) order: (2,1),(2,2),(2,3). First pops (2,1) -> valid, choose 1, push (6,1). heap: (2,2),(2,3),(6,1). Second pops (2,2) -> valid, choose 2, push (6,2). heap: (2,3),(6,1),(6,2). Third pops (2,3) -> valid, choose 3. Output: 1 2 3. Good.
Now, what about a scenario where after some updates, the minimal z is tied between a course that we just updated and another? That's fine.
Now, ensure that we don't have off-by-one errors in reading. Good.
Now, I think solution is correct.
Now, consider if the problem expects us to output a newline at the end. Usually yes. We can add a newline: sys.stdout.write(' '.join(map(str, result)) + '\n')
But not necessary.
Now, I'll produce final answer.
But before final, consider alternative interpretation: Could x be defined as sum of IQs of the last two students who enrolled in that course, but if only one, then that student's IQ; but what about when count=0? x=0. That's clear.
Now, we must check if there is any hidden nuance: The problem might be from Code Monk series (HackerEarth). Typically they expect O((C+P) log C) solution with heap.
Now, we'll finalize.
We should also consider the possibility that the number of initial students N might be less than C, and the initial assignment: "the i^th student chooses the i^th course." So indeed first N courses get one student each.
Now, possible alternative: Could the initial N students be assigned to any courses? The statement says: "i-th student chooses the i-th course." So yes.
Now, final code.
Potential memory improvement: Not needed.
Now, answer.
Wait, what about when we compute x for a course with count >=2? Should we consider the order? Yes, sum of last two. Our update ensures that after each enrollment, we shift.
Now, we should also consider if the course becomes count=2 after enrollment, we correctly compute x as sum of the two students. Good.
Now, I think we are done.
Now, let's produce final answer.
But I'll also write a brief explanation in final solution.
Now, final. ```python
import sys
import heapq
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
C = int(next(it))
P = int(next(it))
N = int(next(it))
Y = [int(next(it)) for _ in range(N)]
X = [int(next(it)) for _ in range(P)]
# state arrays, 1‑based indexing
cnt = [0] * (C + 1) # number of enrolled students
last1 = [0] * (C + 1) # IQ of the most recent student
last2 = [0] * (C + 1) # IQ of the second most recent (if any)
cur_z = [0] * (C + 1) # current z = x * cnt
# initial courses 1..N have one student each
for i in range(1, N + 1):
cnt[i] = 1
last1[i] = Y[i - 1]
cur_z[i] = Y[i - 1] # Y[i-1] * 1
# courses N+1..C are empty – already zero
heap = []
for i in range(1, C + 1):
heapq.heappush(heap, (cur_z[i], i))
result = []
for iq in X:
# discard stale heap entries
while True:
z, cid = heapq.heappop(heap)
if z == cur_z[cid]:
break
result.append(cid)
old_cnt = cnt[cid]
old_last1 = last1[cid]
new_cnt = old_cnt + 1
if old_cnt == 0:
new_last1 = iq
new_last2 = 0
else:
new_last2 = old_last1
new_last1 = iq
# compute new x and new z
if new_cnt == 0:
x = 0
elif new_cnt == 1:
x = new_last1
else:
x = new_last1 + new_last2
new_z = x * new_cnt
# update the course
cnt[cid] = new_cnt
last1[cid] = new_last1
last2[cid] = new_last2
cur_z[cid] = new_z
# push the updated entry
heapq.heappush(heap, (new_z, cid))
sys.stdout.write(' '.join(map(str, result)) + '\n')
if name == "main":
main()