Skip to content

Instantly share code, notes, and snippets.

@mastersobg
Created January 26, 2013 13:21
Show Gist options
  • Select an option

  • Save mastersobg/4642352 to your computer and use it in GitHub Desktop.

Select an option

Save mastersobg/4642352 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
import javax.management.RuntimeErrorException;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
int n, k;
int a, b, c, r;
void solve() throws IOException {
n = ni();
k = ni();
a = ni();
b = ni();
c = ni();
r = ni();
int[] arr = new int[4 * k];
arr[0] = a;
for (int i = 1; i < k; ++i) {
int temp = (int) (((long) b * (long) arr[i - 1]) % (long) r);
temp = (temp + c) % r;
arr[i] = temp;
}
int[] lastEl = new int[k];
System.arraycopy(arr, 0, lastEl, 0, k);
int last = 0;
int i = k;
for (int j = 0; i < n && j < 3 * k; ++i, ++j) {
int element = next(lastEl);
arr[i] = element;
int pos = remove(lastEl, arr[i - k]);
lastEl[pos] = element;
last = element;
}
if (i == n) {
out.println(last);
return;
}
int[] v = new int[k + 1];
for (i = 0; i < v.length; ++i)
v[i] = arr[arr.length - k - 1 + i];
int end = (n - i - 1) % v.length;
out.println(v[end]);
}
int next(int[] arr) {
Arrays.sort(arr);
int find = 0;
for (int i = 0; i < arr.length; ++i)
if (find != arr[i])
return find;
else
find++;
return find;
}
int remove(int[] arr, int el) {
for (int i = 0; i < arr.length; ++i)
if (arr[i] == el)
return i;
throw new RuntimeException();
}
public Solution() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
int t = ni();
for (int it = 0; it < t; ++it) {
out.print("Case #" + (it + 1) + ": ");
solve();
}
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Solution();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment