By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.
In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.
Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).
Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.
To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:
"Success" if the activation was successful.
"Already on", if the i-th collider was already activated before the request.
"Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.
The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:
"Success", if the deactivation was successful.
"Already off", if the i-th collider was already deactivated before the request.
You don't need to print quotes in the output of the responses to the requests.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of colliders and the number of requests, correspondingly.
Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) — activate the i-th collider, or "- i" (without the quotes) — deactivate the i-th collider (1 ≤ i ≤ n).
Output
Print m lines — the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.
Examples
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on
Note
Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3".
We need to solve a problem: given n up to 100k, m up to 100k. Initially all off. For each request, either "+ i" or "- i". We need to output appropriate messages.
For activation: if already on -> "Already on". Else, check if there exists any currently activated collider j such that gcd(i,j) != 1. If yes, output "Conflict with j" (any such j). Otherwise, activate and output "Success".
For deactivation: if already off -> "Already off". Else, deactivate and output "Success".
The challenge is efficient detection of conflict: need to know if any active number shares a common factor >1 with i.
We need to maintain set of active numbers. n up to 1e5, m up to 1e5. For each activation, we could factor i, then check for each prime factor p of i whether any active number is a multiple of p (i.e., there is some active number that shares this prime). If yes, we can output one such active number (maybe the smallest? any). So the key is to maintain, for each prime p (<= n), a set or count of active numbers that are multiples of p. Since n is 1e5, primes up to 1e5. The number of distinct prime factors of a number <= 1e5 is at most ~6 (since product of first 7 primes > 1e5). Actually maximum distinct prime factors for numbers <= 100k is about 6 (235711*13=30030, times 17=510510 >100k so max 6). So per activation we can factor i in O(sqrt(i))? But with precomputation of smallest prime factor (SPF) array up to n, we can factor quickly O(log i). So overall O(m log n) and O(n) precomputation.
But we need to know if there is conflict: we need to know for any prime factor p of i, if there exists at least one active number that is a multiple of p. If multiple primes have conflicts, we need to output any conflicting active number. We can also store for each prime p one example active number (maybe the smallest one or any). Since numbers are unique (colliders are distinct), we can maintain a map from prime to set of active numbers, but we need to get one quickly. However, we also need to remove numbers when deactivated from these prime sets.
Simplest: maintain an array "active" boolean of size n+1. For each prime p, maintain a set (maybe a list) of active numbers that are multiples of p. But we need to support adding and removing numbers from these sets. Since each number i contributes to all its prime divisors, and number of prime divisors is small, we can maintain e.g. for each prime p a count of how many active numbers are multiples of p, and also possibly store one representative (e.g., the first one encountered) but when that number is deactivated we need to provide another if count>0. However, we can just store a count, and if conflict exists, we need to output a specific j. So we need to retrieve any active number that is a multiple of p. Could also store for each prime p the set of active numbers, but using a set per prime (like a hash set) might be heavy: total number of insert/delete operations across all primes is O(m * number of prime factors) = up to 600k, which is fine. But we also need to quickly pick any element from set, e.g., the first element (like *set.begin() if using C++ set). Using Python, we could use a dict mapping prime -> set, but sets are hash sets and retrieving an arbitrary element (e.g., next(iter(set))) is O(1) average. However, Python set's pop() is arbitrary but removes; we need just to peek. We can use next(iter(prime_set[p])) to get one element. But creating iter each time is fine. Or we can store for each prime a list? But removal from list is O(n) unless we use set. Since the sizes are small, sets are okay.
Alternatively, we can maintain an array "conflict_number[p]" that stores some active number that is multiple of p, and we update it when numbers become active/inactive. But careful: if we only store one number per prime, we need to update it correctly when that number is deactivated. We could store the count and also maintain a stack for each prime? But because each number may be added to multiple primes, we need to know for each prime, if the current stored number is deactivated, we need to pick another from the list. Since the total number of numbers is small and each number appears in at most few prime sets, we could maintain for each prime a set, and when we need a conflicting number, we can pick any from the set (e.g., the smallest). That's straightforward.
Therefore, approach: precompute all primes up to n (or spf). For each i from 1 to n, compute list of its distinct prime factors (or include duplicates? but gcd condition uses distinct primes; if two numbers share a factor, they must have at least one common prime divisor. So it's enough to consider distinct prime factors). So for each number, we store its prime factors set.
Initialize: active = [False]*(n+1). For each prime p up to n, maintain a set active_multiples[p] (maybe using Python set). But there are many primes up to n, about 10k. Using a dictionary mapping prime to set is fine; we can allocate dict only for primes that actually appear? But each number up to n will have primes up to n, so we might have up to n keys. But 100k keys each with a set is okay? 100k sets empty initially might be memory heavy (each empty set overhead ~72 bytes). That's about 7 MB, okay maybe but 100k * 72 = 7.2 MB. But we also have many other structures, still acceptable. However in Python, 100k dict entries each with a set may be too heavy? Let's approximate: each dict entry overhead ~72 bytes? Actually Python's dict entry overhead is around 72 bytes for key+value? Not exactly; each entry is a pointer to a PyObject key and value, plus hash etc. The set itself is a separate object. So 100k sets could be ~8-10 MB each? Wait: each empty set object takes about 216 bytes (maybe more). Actually let's check: sys.getsizeof(set()) is 216 bytes on 64-bit Python. Then each dict entry key is integer (28 bytes) plus the dict overhead. 100k * 216 = 21.6 MB just for empty sets, plus dict overhead. That might be high but possibly still okay for memory limit (likely 256 MB). But we might also have many sets non-empty; but still, 100k empty sets is a bit wasteful. We can avoid creating sets for all primes initially. Instead, use a dict mapping prime to set, but create set only when needed. Since we will only use primes that appear as factors of numbers that are ever activated. At worst, all numbers from 1 to n might be activated, and each number's prime factors are distinct primes? But many primes are used. The number of primes up to 1e5 is 9592. So at most 9592 distinct primes. Actually primes up to 100000 is about 9592. So we have at most 9592 primes. That's even smaller. So we can just precompute list of primes and use an array of size n+1? But we can index by prime up to n, but not all numbers are primes. We can allocate a list of size n+1 where each element is a set, but that would be huge overhead for non-prime indices; but we can store None for non-primes. Actually we can allocate a dictionary mapping prime to set, with keys only primes. Since we know the primes up to n, we can pre-allocate a list of size n+1 and for prime indices we assign a set; but that would be memory for 100001 list entries, each a reference (8 bytes) so about 0.8 MB, plus sets for primes only (9592 sets). So we can do:
is_prime = [False]*(n+1)
prime_factors = [[] for _ in range(n+1)] # distinct prime factors for each number
But for n=100k, a list of 100001 empty lists is okay (each empty list overhead maybe 56 bytes? Actually Python list is an array of pointers; list object overhead. A list of 100001 empty lists would allocate 100001 list objects, each with overhead. That's heavy: 100k * 56 = 5.6 MB? Possibly too much. Better to compute prime factors on the fly using SPF and store for each number we might need? Since m up to 1e5 and numbers i up to n, we might need prime factors for each i that appears in requests. We could compute them at request time using SPF and cache them if needed again. That's typical: Precompute SPF for all numbers up to n using sieve O(n log log n). Then factor(i) returns list of distinct primes. Since a number might be requested multiple times, we can cache its prime factors in a dictionary.
Now for active multiples per prime: we can maintain a dict prime_to_set: key=p, value=set of active numbers that have p as factor. But we also need to quickly get any element. Python set pop() removes and returns arbitrary element; but we just need to peek. However, we can just do next(iter(set)) which returns some element without modifying. That's O(1) average? Possibly it creates an iterator and calls next, which is fine.
So algorithm:
Precompute spf array of size n+1.
Initialize: active = [False]*(n+1) (bool list)
Initialize prime_sets = {} (dict int -> set)
For each request:
If "+ i":
if active[i]: print("Already on")
else:
# factor i distinct primes
primes = distinct_primes(i) (using spf)
conflict_found = False
conflict_j = None
# Check each prime p:
for p in primes:
if p in prime_sets and prime_sets[p]:
# there is at least one active number with this prime factor
# pick any j from the set
conflict_j = next(iter(prime_sets[p]))
conflict_found = True
break
# But also need to check if there is a conflict with a number that shares a composite factor but no common prime? That's impossible: if gcd(i,j) > 1, they share at least one prime factor. So checking primes is enough. However, careful: i could be 1. 1 has no prime factors. gcd(1,j)=1 for any j, so always safe. So for i=1, primes list empty, no conflict.
if conflict_found:
print(f"Conflict with {conflict_j}")
else:
# Activate: set active[i]=True; for each p in primes, add i to prime_sets[p] (creating set if not exist)
active[i]=True
for p in primes:
if p not in prime_sets:
prime_sets[p] = set()
prime_sets[p].add(i)
print("Success")
If "- i":
if not active[i]: print("Already off")
else:
active[i]=False
# Remove i from all its prime sets
primes = distinct_primes(i) # get from cache or compute
for p in primes:
prime_sets[p].discard(i) # remove if exists, ignore if not
# optional: if set becomes empty, we could delete key to save memory, but not necessary
print("Success")
We need to be careful about i=1: it has no primes. So activation: no conflict, just active[1]=True, no entry in prime_sets. Deactivation: similarly.
Now time complexity: factorization O(log i) per request (since each step divides by spf). For each activation/deactivation, we iterate over distinct primes (max ~6). So total O(m * (log n + small)) which is fine.
Memory: active array size n+1 (bool). spf array size n+1 (int). prime_sets dictionary with at most 9592 keys, each set contains numbers. The sum of sizes across sets equals total active numbers * number of prime factors per number, which is at most (active count) * 6, active count <= n, so at most 600k entries. That's fine.
Now, the tricky part: Checking for conflict: we only look at primes of i. But consider scenario: i shares a prime factor with an active j, that's conflict. But what if i shares no prime factor with any active, but there is some active j such that gcd(i,j) > 1 due to composite factor like both 4 and 6 share factor 2? Wait, 4 prime factors {2}, 6 prime factors {2,3}. So they share prime 2. So checking primes is sufficient. Good.
But what about i=0? i is between 1 and n inclusive, so fine.
Now test sample: n=10, m=10. Should match.
Potential pitfalls:
When conflict is found, we break after first prime with non-empty set. But that set may contain i itself? But i is not active yet, so it cannot be in the set. So no self-conflict.
However, consider scenario: i=6, primes {2,3}. Suppose only active is 6? But i not active, so sets for 2 and 3 contain 6? That would cause conflict. That's correct.
Deactivation: we remove i from sets. If we later reactivate i, we need to check conflict again. Works.
Caching primes: we can store prime_factors[i] after first compute. Use list.
Implementation details:
Read n, m.
Precompute spf for 1..n using linear sieve or simple sieve.
We'll do: spf = list(range(n+1)); for i in range(2, int(n**0.5)+1): if spf[i]==i: for j in range(i*i, n+1, i): if spf[j]==j: spf[j]=i.
That's O(n log log n). For n=1e5 fine.
Function get_primes(x):
res = []
while x > 1:
p = spf[x]
res.append(p)
while x % p == 0:
x //= p
optionally deduplicate but the above loop adds each prime once because we divide out all factors of p. That yields distinct primes. Ensure: after while x%p==0 we get x with p removed. Then continue.
return res
But note: For x=1, loop doesn't run, return empty.
For caching: use primes_cache = [None]*(n+1) list; compute when needed and store.
def get_primes_cached(x):
if primes_cache[x] is None:
primes_cache[x] = get_primes(x)
return primes_cache[x]
Alternatively, compute on demand and store.
Now, prime_sets: dict of int->set.
Edge Cases:
Multiple conflict: we can return any j. The algorithm returns the first j found among primes. That's fine.
If conflict occurs, we don't activate. So we don't modify sets.
Already on: we print Already on.
Already off: print Already off.
Potential performance issues: Python's set iteration overhead is fine.
But one nuance: When we check for conflict, we need to ensure that for each prime p, the set may contain numbers that are not active? We only add when activating, and remove when deactivating. So sets are consistent.
Double-check: When we deactivate, we use discard to remove i from the set. If for some reason i not in set (maybe bug), discard is safe.
Now test with sample:
n=10,m=10
Requests:
+6: primes of 6: {2,3}. sets empty -> Success; active[6]=True; add 6 to sets[2]={6}, sets[3]={6}
+10: primes 2,5. Check p=2: set has 6 -> conflict with 6. Output Conflict with 6.
+5: primes 5. set[5] empty, set[2] has 6 but not checking 2? Wait we only check primes of 5: 5. set[5] empty -> Success. Add 5 to set[5]={5}
-10: 10 is off (since activation failed) -> Already off? Actually status: active[10] is false (not activated). So request "-10": should output Already off. Indeed sample shows "Already off" after -10.
-5: deactivate 5: active[5] is true -> Success; remove 5 from set[5] (becomes empty)
-6: deactivate 6: active[6] true -> Success; remove 6 from set[2] and set[3] (both become empty)
+10: activate 10: primes 2,5. sets[2] empty, sets[5] empty -> Success; add 10 to sets[2]={10}, sets[5]={10}
+3: primes 3; set[3] empty -> Success; add 3 to set[3]={3}
+6: primes 2,3; check p=2: set[2] has 10 -> Conflict with 10. Output "Conflict with 10". Indeed sample says Conflict with 10.
+3: primes 3; set[3] has 3 -> Already on? Actually active[3] is true -> Already on. Sample shows Already on.
Matches.
Now we need to handle case where conflict with multiple, we can output any.
Now complexity: factorization for each request. But we could precompute all distinct prime factors for all numbers up to n, storing in list of lists, to avoid recomputation. Since n=1e5 and number of distinct primes per number is small, total storage would be sum_{i=1}^n distinct primes count. The sum of distinct prime factors over numbers 1..n is about n log log n? Actually sum_{i=1}^n ω(i) (number of distinct primes) ~ n log log n. For n=1e5, that's about 1e5 * ~2.5 = 250k, which is small. So we can precompute once and store. That may be simpler and faster. Let's do that.
Approach: precompute primes up to n (or spf) and then for i from 2 to n, compute distinct primes and store. For 1, empty list.
We can do:
spf = [0]*(n+1)
sieve
for i in range(2,n+1):
if spf[i]==0:
spf[i]=i
for j in range(ii, n+1, i):
if spf[j]==0:
spf[j]=i
But careful: ii may overflow? For n=1e5, i up to 316, i*i up to 100k. So okay. But we need to set spf for primes themselves. Actually we can use linear sieve to get spf for all numbers in O(n). But simple is okay.
Alternative: compute minimal prime factor for all numbers using classic sieve:
spf = list(range(n+1))
for i in range(2, int(n**0.5)+1):
if spf[i]==i:
for j in range(i*i, n+1, i):
if spf[j]==j:
spf[j]=i
That yields spf for composites only, primes remain themselves.
Then compute prime_factors list:
prime_factors = [[] for _ in range(n+1)]
for i in range(2, n+1):
x = i
while x > 1:
p = spf[x]
prime_factors[i].append(p)
while x % p == 0:
x //= p
For i=1, empty list.
But this recomputes for each i, total operations sum of number of prime factors with multiplicity? Actually inner while loop for i runs through each i separately, leading to O(n log n) maybe? But we can compute more efficiently by using DP: For each i, prime_factors[i] = prime_factors[i // spf[i]] plus maybe new prime if not already? But need distinct. Simpler: we can compute distinct primes by iterating from 2 to n and for each prime, add it to multiples? Actually we can precompute using a sieve that for each multiple of p, add p to the list of that number. That is O(n log log n) and easy. For each prime p (precomputed list), for multiple m of p, add p to prime_factors[m]. That yields distinct primes? However, if a number has multiple prime factors, it will get added once per prime from that method. That's fine. But we need distinct primes; this method adds each prime exactly once to each multiple. So total operations = sum over primes p of n/p ≈ n log log n. For n=1e5, that's okay.
Simpler: we can compute prime factors on the fly with caching using spf; that's also fine.
But to avoid potential TLE due to Python's while loops for each request, we can precompute. However, factorization with spf is O(log i) and m=1e5, log i <= about 6 steps, so total steps ~600k, which is trivial. So we can do caching: compute when needed and store. That's probably fine.
But there is a nuance: The conflict check only needs to know primes of i; but we also need to know primes of i for deactivation to remove from sets. So caching helps.
We'll implement a class or just global arrays.
Now about prime_sets: we used dict of sets. Could also use list of sets indexed by prime numbers, but we need to know which indices are primes. However, we can just use a list of sets of size n+1, where sets[p] is only meaningful for prime p. But then we have to allocate list of size n+1 with empty sets for all indices; but we can initialize with None and create set when needed. That's similar memory: list of 100001 references (8 bytes each) ~0.8 MB, plus sets for primes. That's acceptable and faster to access than dict lookup. Let's weigh: dict lookup per prime involves hashing, while list indexing is O(1) constant. Since we will do many operations (up to ~600k), list might be faster. But we need to know which indices are primes? Actually we can use list and for any p (prime or composite) we may still access, but we will only access p that are prime factors of some numbers. So we might access composite indices? For composite numbers as prime factors? No, prime factors are primes. So p will always be prime. But still we need to create sets only for primes we encounter. So we can have an array prime_set = [None]*(n+1). When we need to add i to p, we check if prime_set[p] is None: then prime_set[p] = set(). Then add i. For removal, we discard. For conflict check, we do if prime_set[p] and prime_set[p]: (i.e., not empty) then get any element: next(iter(prime_set[p])). That's fine.
But note: for p > n? p <= n because i <= n and its prime factors <= i <= n.
Thus, using list is simpler and likely faster. Overhead: list of length n+1 of None, each reference 8 bytes => 800KB for n=100k, fine. Sets created only for primes used. So good.
Now we need to handle case where p=1? Not possible, since primes start from 2. So okay.
Now check conflict: we need to iterate through primes of i. But we must be careful: if i has a prime factor p, but the set for p contains some j, that j is guaranteed to be active and share prime p, so gcd(i,j) > 1. However, what if i itself is active? That's Already on case, so we won't check. So fine.
But also note: It's possible that i shares a factor with some active j but that active j's prime factor set doesn't contain p because we only added j to sets for its prime factors. Yes, if j is active, we added it to sets for all its prime factors. So any common prime factor will be in j's prime factors, thus j is in set for that p. So our check works.
Edge Cases: i=1 has no prime factors. So conflict cannot occur; we can always activate if not already on.
Now the algorithm seems correct.
But wait: Are there any cases where conflict could exist but not detected by checking primes? Suppose an active number j=6 (primes 2,3) and i=4 (primes 2). Check p=2: set[2] contains 6 => conflict. OK.
What if i and j share a composite factor but not a prime? That's impossible: any composite factor is product of primes; if they share a composite factor, they share at least one prime factor.
So done.
Now implement.
Implementation Steps:
Read n, m.
Precompute spf up to n using sieve.
spf = [0](n+1)
for i in range(2, n+1):
if spf[i]==0:
spf[i]=i
if ii <= n:
for j in range(i*i, n+1, i):
if spf[j]==0:
spf[j]=i
Actually we need to also set spf for primes themselves. The above sets spf for primes to themselves. For composites, it sets spf to smallest prime divisor. For numbers that are not set (like 1) we keep spf[1]=1? We'll handle separately.
Alternatively, use standard:
spf = list(range(n+1))
for i in range(2, int(n**0.5)+1):
if spf[i]==i:
for j in range(i*i, n+1, i):
if spf[j]==j:
spf[j]=i
That's simpler.
For i=1, spf[1]=1.
Initialize active = [False]*(n+1)
Initialize prime_sets = [None]*(n+1) # each entry for prime p will be a set of active numbers having p as factor
Define function get_primes(x):
if prime_factors_cache[x] is not None:
return prime_factors_cache[x]
orig = x
res = []
while x > 1:
p = spf[x]
res.append(p)
while x % p == 0:
x //= p
prime_factors_cache[orig] = res
return res
For x=1: while loop condition false, returns [].
Loop over m requests:
Read line: split -> cmd, i_str -> i = int(i_str)
if cmd == '+':
if active[i]:
print("Already on")
else:
primes = get_primes(i)
conflict = None
for p in primes:
s = prime_sets[p]
if s is not None and s:
# pick any element
# In Python set, iterating gives elements. next(iter(s)) yields one element
conflict = next(iter(s))
break
if conflict is not None:
print(f"Conflict with {conflict}")
else:
active[i] = True
for p in primes:
if prime_sets[p] is None:
prime_sets[p] = set()
prime_sets[p].add(i)
print("Success")
else: # '-'
if not active[i]:
print("Already off")
else:
active[i] = False
primes = get_primes(i)
for p in primes:
if prime_sets[p] is not None:
# remove i from set
prime_sets[p].discard(i)
print("Success")
Need to be careful: For i=1, primes = [] so loops skip.
Now test with sample.
But there might be a nuance: The conflict detection logic may fail if i shares a prime factor with an active number j but that j is also a multiple of some other primes, but j's entry in prime_sets[p] is present. However, what if there are multiple active numbers sharing the prime p? It's fine.
Now consider scenario where i is prime p itself. Then primes list = [p]. If there is any active number that is a multiple of p (including maybe p itself if already active but that's Already on case), conflict. Good.
Now consider scenario where i is composite but shares prime factor with j that is 1? No.
Now ensure that we don't have false positives: Suppose i has prime factor p, but the only number in prime_sets[p] is i itself? But we haven't added i yet because we are checking before activation. So prime_sets[p] contains only currently active numbers; i is not active. So no self conflict.
Now about removing from sets when deactivating: we need to ensure that after removal, the set may become empty. Not deleting is fine. But later when checking conflict, we will check if set exists and non-empty. So None or empty will be false.
Now complexity: For each activation or deactivation, we factor i. But we may factor the same i multiple times (if toggled). With caching, we factor only first time. So okay.
Case: +6, +10: conflict with 6 because both share 2. Works.
Now one more nuance: When we check conflict for i, we iterate primes in order. What if i has multiple primes and conflict exists for two? We break on first. That's fine.
Now potential performance issue: When prime_sets[p] is a set, next(iter(s)) requires creating an iterator and calling next; that is fine. But what if set is large? The size of prime_sets[p] can be up to number of multiples of p that are active, which could be up to n/p. For p=2, it could be up to 50000. Still, iter(s) gives an iterator; next() picks the first element according to set iteration order. This is O(1) average.
Now memory: prime_sets as list of None/set; prime_factors_cache as list of lists. For n=100k, prime_factors_cache will hold at most n+1 lists; but many of them empty? Actually for i=1, empty list; for each i we will store list of primes. The total number of stored primes across all numbers is sum of ω(i) (distinct primes) which is approx n log log n ~ 1e5 * 2.5 = 250k. That's fine. But we allocate a list of length n+1, each entry is a list reference (8 bytes) -> 800KB. The lists themselves have overhead; but total memory maybe a few MB.
Alternatively, we can compute primes on the fly and cache only when needed. But we can also just compute on the fly each time without caching; factorization with spf is cheap. But then for each deactivation we factor again; but that's still okay. However, we need to be careful: For each activation and deactivation we factor i. In worst case m=1e5, each factorization O(log i) steps; total steps maybe around 600k. That's trivial. So we can skip caching to simplify code. But we need primes for both activation and deactivation. For deactivation we need to know primes to remove i from sets. So we could factor each time without caching. However, if the same i appears many times, we could factor multiple times; still total steps < 1e5 * ~6 = 600k, which is fine. So we could just factor on the fly using spf without caching. That simplifies memory. Let's consider that.
Simplify: we only precompute spf. Then define a function get_primes(x) that returns list of distinct primes for x. It uses while loop with spf. Since we call it for each request (both + and -) at most 2*m times? Actually each request either + or -, each calls get_primes (except maybe when Already on/off we don't need factors). But we call get_primes for + when not already on, and for - when active. But we may also call for - when already off? No, we skip. So at most m calls for operations that actually modify (activation and deactivation) plus conflict check? Actually we call get_primes for conflict check and for adding/removing. For activation, we need primes for conflict check and also for adding. We can compute once and reuse. So we can compute primes = get_primes(i) at start of activation block, then use for conflict and adding. Similarly for deactivation. So each successful or failed activation (except Already on) will compute primes once; each successful deactivation (except Already off) will compute primes once. So at most m times. So total factorization steps <= m * max distinct primes (<=~6), plus divisions. So overall maybe 600k iterations. That's negligible.
Thus we can skip caching prime factors to simplify code.
Let's adopt this: no caching of prime factors; just compute on the fly.
Now we need to compute spf quickly. Use sieve as described.
Implementation details: In Python, for loops over range with step can be optimized, but n=100k so fine.
Let's write sieve:
def sieve_spf(n):
spf = list(range(n+1))
spf[0] = 0 # not used
spf[1] = 1 # but we won't use for factorization of 1
limit = int(n**0.5) + 1
for i in range(2, limit):
if spf[i] == i: # i is prime
for j in range(i*i, n+1, i):
if spf[j] == j:
spf[j] = i
return spf
This sets spf for all numbers. For primes > sqrt(n), they remain as themselves.
Now function get_distinct_primes(x, spf):
primes = []
while x > 1:
p = spf[x]
primes.append(p)
while x % p == 0:
x //= p
return primes
Now prime_sets: list of None or set. We'll use prime_sets = [None] * (n+1). But note that indices up to n.
Now conflict detection: For each p in primes:
s = prime_sets[p]
if s and s: Actually if s is not None and s (non-empty). In Python, if s will be true if set is non-empty, but if s is None, it's false. So we can do:
code
if prime_sets[p]:
# since prime_sets[p] might be None or empty set; None is falsy, empty set is falsy; non-empty set is truthy.
conflict = next(iter(prime_sets[p]))
break
But careful: prime_sets[p] could be an empty set, but we treat as falsy. So if prime_sets[p]: works because empty set is False. But if prime_sets[p] is None, also False. Good.
Now for adding: for p in primes:
if prime_sets[p] is None:
prime_sets[p] = set()
prime_sets[p].add(i)
Now removal: for p in primes:
if prime_sets[p] is not None:
prime_sets[p].discard(i)
# Optionally, if not prime_sets[p]: we could set to None, but not needed.
Now about conflict reporting: The problem says: If conflict occurs with several colliders simultaneously, you should print the number of any of them. So returning the first found is okay.
Now let's consider another scenario: If i is large prime near n, and there is an active number j that is a multiple of that prime (i itself? j could be i only if already on, but we skip). j could be i's multiple only if i is prime and j = i * k <= n. For example n=100000, prime p=99991, multiple 99991*2 > n, so only itself. So conflict only if i itself is already on. So fine.
Now we must ensure that we correctly handle i=1: no primes. Conflict check loop doesn't run, conflict remains None -> Success.
Now about time: The main loop may use for p in primes: each iteration small. The set operations are O(1) average.
Now possible pitfalls: In Python, next(iter(s)) on an empty set raises StopIteration, but we checked that s is truthy, so it's non-empty.
Now we should also consider that when activating a number i, we need to check that there is no conflict with any active j. Our method checks each prime factor of i. But what if i has no prime factors (i=1)? It's fine. Also, what if there is an active j such that gcd(i,j) > 1 but i and j share a factor that is not a prime factor of i? That's impossible: any common divisor > 1 must contain at least one prime factor of i.
Thus solution is correct.
Now we should also think about numbers that are powers of primes: i=4 (prime factors [2]) and j=6 (primes [2,3]) -> conflict via 2. Works.
Now consider i=6 and j=15: gcd=3, prime 3 is factor of i, so conflict.
Now consider i=30 (2,3,5) and j=21 (3,7): conflict via 3. Check: set[3] contains j -> conflict.
Now check deactivation removal: remove i from all prime sets. That works.
Now potential bug: When we deactivate, we call get_primes(i) to get primes. But what if i is 1? get_primes returns [], loops skip.
Now what about duplicate activation/deactivation: Already on/off handled.
Now check memory: prime_sets list of size n+1, each entry either None or a set. For each active number i, it gets added to sets for each distinct prime factor. So total number of entries across sets is at most (number of active numbers) * (max distinct primes per number) <= n * 6 = 600k. That's fine.
Now we need to read input efficiently, as m up to 1e5, lines. Using sys.stdin.read() and split.
We'll implement:
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
spf = list(range(n+1))
spf[0] = 0
spf[1] = 1
import math
lim = int(math.isqrt(n))
for i in range(2, lim+1):
if spf[i] == i:
step = i
start = ii
for j in range(start, n+1, step):
if spf[j] == j:
spf[j] = i
# Alternatively, we can use a faster loop.
active = [False](n+1)
prime_sets = [None]*(n+1) # index prime -> set of active numbers containing that prime
code
out_lines = []
for _ in range(m):
cmd = next(it)
i = int(next(it))
if cmd == '+':
if active[i]:
out_lines.append("Already on")
else:
# get distinct primes of i
primes = []
x = i
while x > 1:
p = spf[x]
primes.append(p)
while x % p == 0:
x //= p
conflict = None
for p in primes:
s = prime_sets[p]
if s:
# non-empty set
conflict = next(iter(s))
break
if conflict is not None:
out_lines.append(f"Conflict with {conflict}")
else:
active[i] = True
for p in primes:
if prime_sets[p] is None:
prime_sets[p] = set()
prime_sets[p].add(i)
out_lines.append("Success")
else: # '-'
if not active[i]:
out_lines.append("Already off")
else:
# deactivate
active[i] = False
# get distinct primes of i
primes = []
x = i
while x > 1:
p = spf[x]
primes.append(p)
while x % p == 0:
x //= p
for p in primes:
s = prime_sets[p]
if s is not None:
s.discard(i)
out_lines.append("Success")
sys.stdout.write("\n".join(out_lines))
Now check for conflict when i has prime factor p, and prime_sets[p] is not None but maybe the set includes numbers that are not active due to some bug? But we maintain carefully: add on activation, remove on deactivation. So correct.
Now we must ensure that when we deactivate, we don't inadvertently remove from sets if the set is None? Already check.
Now, what about numbers that are prime but we store them in prime_sets for that prime. If later we activate a number that is a multiple of that prime, we will see conflict. Good.
Now time complexity: Sieve O(n log log n) ~ 100k; loops for each request: factorization while loop, number of iterations equal to number of distinct primes (<= ~6) plus inner while loops to divide out multiples; but those inner while loops reduce x quickly, so total divisions per factorization <= total prime factors with multiplicity? Actually the code:
while x > 1:
p = spf[x]
primes.append(p)
while x % p == 0:
x //= p
This inner loop will divide x by p until it's no longer divisible. So total number of divisions is O(number of prime factors with multiplicity), which for numbers up to 1e5 is at most about log2(1e5) ~ 17 (worst case powers of 2). Actually 2^16=65536, 2^17=131072 > 1e5, so max 16 divisions? So at most 16 operations. So fine.
Now the for p in primes loop is small.
Now set operations: add, discard, iteration. Good.
Now we need to ensure that the conflict detection picks any conflicting j. Our method picks the first element in the set for the first prime that has non-empty set. That's okay.
Potential issue: When a number is deactivated, we remove it from all prime sets. However, there might be multiple numbers sharing the same prime, and we might have removed the representative number that might be used later for conflict detection. That's fine because the set still contains other numbers if any.
Now, what about the scenario where a number i is activated but it shares a prime factor p with some active j, but also maybe shares a different prime factor with another active k. Our conflict detection stops at first such prime; that's fine.
Now we should test with a custom case: n=6, requests: +4, +6.
+4: primes [2]; sets[2] empty -> Success; add 4 to set[2]={4}
+6: primes [2,3]; check p=2: set[2] has 4 -> conflict with 4. Output conflict. Works.
Now test with deactivation then activation: +4, -4, +6.
+4: success.
-4: success, remove 4 from set[2] (now empty).
+6: primes [2,3]; set[2] empty, set[3] empty -> success. Good.
Now test with multiple activations that share prime: +6, +10. Already did. Output conflict with 6.
Now test with conflict with multiple choices: n=6, +6, +3 (6 and 3 are relatively prime? gcd(6,3)=3 >1, not relatively prime). So conflict. +6: success. +3: primes [3]; set[3] has 6? Actually 6's primes are [2,3]; set[3] contains 6. So conflict with 6. Our code returns 6. That's fine.
Now test with numbers that are 1: +1, +2, +3: Should all be success because 1 is coprime with all. +1 success, +2 success (2 prime factor 2, set[2] empty), +3 success. Works.
Now test with deactivation of a number that is not active: -2 after all off: Already off.
Now test with activation of already on: +2, +2: first success, second Already on.
Now edge: n=100000, m=100000 random, should be fine.
Now potential improvement: In conflict detection, we iterate primes in the order they appear during factorization. For numbers like i=30, primes might be [2,3,5] (order from factorization: while loop yields smallest prime first typically because spf gives smallest prime). That's fine.
Now we must be careful: prime_sets[p] might be None initially, but we check if prime_sets[p]: . In Python, None is falsy, empty set is falsy, non-empty set is truthy. So if prime_sets[p]: works for both None and empty set. However, if we set prime_sets[p] = set() and later it becomes empty after removals, it's still a set object, but empty, so if prime_sets[p]: will be False. So fine.
Now we should consider that for large n, the list prime_sets of size n+1 might contain many None references, which is fine.
Now one nuance: In sieve, we need spf for all numbers up to n. Our current method: spf = list(range(n+1)). Then for i in range(2, int(sqrt(n))+1): if spf[i]==i: for j in range(i*i, n+1, i): if spf[j]==j: spf[j]=i. This sets spf for composites. For primes larger than sqrt(n), spf remains i (the prime itself). For 1, we leave as 1. That's fine.
But careful: For i=4, spf[4] will be set to 2 because 2 is prime and we set for multiples of 2? Actually we start i=2, spf[2]==2, then set for j=4,6,8,... if spf[j]==j then set to 2. So spf[4] becomes 2. For i=3, set for 9,12,15,... but 6 already has spf=2, so condition spf[6]==6 false, skip. So works.
Now for factorization of numbers like 1, while loop condition false, returns empty.
Now ensure that we import math for sqrt (isqrt). We can use int(n**0.5) or math.isqrt for Python 3.8+.
Now we need to output each response line. Using list and join is efficient.
Now confirm sample:
Input:
10 10
6
10
5
10
5
6
10
3
6
3
Our algorithm:
Initialize spf, active all False, prime_sets all None.
Now we should consider cases where conflict arises with multiple numbers and we need to output any. Our method picks the first element of the set for the first prime factor that has non-empty set. That's fine.
Now potential issue: When i has prime factor p and prime_sets[p] contains some j, but j is i itself? Not possible because i not active yet. So fine.
Now about memory: prime_sets list of size n+1, each entry either None or a set. The sets themselves will contain integers. For n=1e5, there could be up to ~100k active numbers, each with up to 6 primes, so total entries 600k. Each integer object is 28 bytes in Python, but they are small ints and may be interned? Actually Python caches small ints from -5 to 256, but larger ints are separate objects. However, storing 600k integers (each maybe up to 1e5) could be heavy: 600k * 28 = 16.8 MB. Plus sets overhead: each set entry uses additional overhead for hash table entry (around 72 bytes?). In Python, a set entry overhead is about 72 bytes (for the pointer and hash). So total memory could be high: 600k * (72+?) maybe 50 MB. But this is still within 256 MB maybe. But we must be careful.
We can reduce memory by storing only one representative per prime? But we need to remove numbers from sets correctly. We could store for each prime a count of active numbers and one example active number. But when we deactivate that example, we need to replace it with another active number if any. To do that, we could maintain for each prime a set but maybe use a list? However, we can reduce memory by not storing the full set, but just a counter and a "representative" number. But we need to be able to pick any active number for conflict, and also when deactivating, we need to update the representative if it's the one being deactivated. We could do:
For each prime p, maintain:
count: number of active numbers that have p as a factor.
one: any active number with factor p (e.g., the most recent added, or a stored value).
When adding i, for each prime p of i, increment count, and set one[p] = i if count becomes 1 (or always set to i). When removing i, for each prime p of i, decrement count, and if count > 0 and one[p] == i, we need to replace one[p] with some other active number that has p. But we don't have a quick way to pick another without storing all. We could store a set of numbers for each prime but that is the set we already had. But we could store for each number i, its prime factors, and for each prime p, we could store a reference to one number, and also maintain a linked list among numbers sharing the same prime? That's more complex.
Given constraints (n,m <= 1e5) and typical memory limits (256 MB), the set approach should be fine. But we need to be mindful of Python overhead. Let's roughly estimate memory consumption.
spf array: list of ints of length n+1. Each int is 28 bytes (but small ints may be shared? Actually each entry is a Python int object, but they are not shared; list stores references to int objects. Each int object ~28 bytes, plus list references 8 bytes each? Actually list stores pointers to PyObject; each pointer is 8 bytes (on 64-bit). So the list of length 100001 has 100001 * 8 = 800k bytes for pointers, plus each int object ~28 bytes, total ~2.8 MB? Wait, if we create list with range, the integers from 0 to n are pre-allocated? In Python, integers are immutable and small integers from -5 to 256 are cached, but larger ints are created. For n=100000, many ints >256 will be created separately. However, using list(range(n+1)) creates distinct int objects for each number? Actually Python caches small ints up to 256, but for larger numbers, each integer is a separate object. So spf list will contain many distinct int objects for numbers >256. That could be memory heavy: 100001 int objects * 28 bytes = 2.8 MB, plus list overhead of 8 bytes per slot = 0.8 MB, total ~3.6 MB. That's okay.
active list: list of bools; bool objects are singletons True/False, so list of references: 100001 * 8 = 0.8 MB. Actually bool is a subclass of int, True/False are singletons, so each reference points to the same object. So memory for active list is just the list of pointers: 0.8 MB.
prime_sets list: length 100001; each entry is either None (a singleton) or a set. So list of pointers: 0.8 MB. For each set, overhead per set: an empty set is ~216 bytes? Actually sys.getsizeof(set()) is 216 on 64-bit CPython. Plus for each element added, additional memory. For each entry in a set, Python uses a hash table. Each entry is a pointer to the int object (which already exists as integer objects for numbers 1..n) and some overhead. Rough estimate: Each set element takes about 72 bytes (for the table entry) plus the int object is shared? Actually each number from 1..n is a distinct integer object (like 100000 is a distinct object). But in Python, small ints are cached up to 256; numbers >256 are created separately when needed. However, when we use integer literals or compute them, Python may reuse the same integer object? Actually, integers are immutable and Python may reuse small ints from -5 to 256. For larger ints, each time you create an integer with the same value, it may or may not be the same object; Python sometimes caches some integers, but generally not for all. But when we have numbers from 1 to n, if we generate them via range or loops, they are created as separate objects. However, in our code, the numbers we add to sets are i from the input (converted to int). Those ints are the same objects as the ones used elsewhere? They are created from string conversion, each conversion yields a new int object? Actually Python may reuse small ints via intern? It doesn't automatically intern ints beyond small range. But we can rely on that each integer from input is a new int object? However, if we have the same number appearing multiple times, each conversion yields a new int object? Actually CPython caches small ints in range -5..256, but for larger ints, each conversion from string creates a new int object, but the interpreter may also reuse some via integer interning? I'm not fully sure; but it's possible that each time we see integer 50000, a