Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is my O(k) solution, which is based on the same idea as above, but runs much faster.</p> <pre><code>import os, sys f = open(sys.argv[1], 'r') T = int(f.readline()) def next(ary, start): j = start l = len(ary) ret = start - 1 while j &lt; l and ary[j]: ret = j j += 1 return ret for t in range(T): n, k = map(int, f.readline().strip().split(' ')) a, b, c, r = map(int, f.readline().strip().split(' ')) m = [0] * (4 * k) s = [0] * (k+1) m[0] = a if m[0] &lt;= k: s[m[0]] = 1 for i in xrange(1, k): m[i] = (b * m[i-1] + c) % r if m[i] &lt; k+1: s[m[i]] += 1 p = next(s, 0) m[k] = p + 1 p = next(s, p+2) for i in xrange(k+1, n): if m[i-k-1] &gt; p or s[m[i-k-1]] &gt; 1: m[i] = p + 1 if m[i-k-1] &lt;= k: s[m[i-k-1]] -= 1 s[m[i]] += 1 p = next(s, p+2) else: m[i] = m[i-k-1] if p == k: break if p != k: print 'Case #%d: %d' % (t+1, m[n-1]) else: print 'Case #%d: %d' % (t+1, m[i-k + (n-i+k+k) % (k+1)]) </code></pre> <p>The key point here is, m[i] will never exceeds k, and if we remember the consecutive numbers we can find in previous k numbers from 0 to p, then p will never reduce.</p> <p>If number m[i-k-1] is larger than p, then it's obviously we should set m[i] to p+1, and p will increase at least 1.</p> <p>If number m[i-k-1] is smaller or equal to p, then we should consider whether the same number exists in m[i-k:i], if not, m[i] should set equal to m[i-k-1], if yes, we should set m[i] to p+1 just as the "m[i-k-1]-larger-than-p" case.</p> <p>Whenever p is equal to k, the loop begin, and the loop size is (k+1), so we can jump out of the calculation and print out the answer now.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload