PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000106. Tìm kiếm nhị phân trên dãy chưa sắp xếp (Out of Sorts)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tìm kiếm nhị phân trên dãy chưa sắp xếp (Out of Sorts)

Out of Sorts

Source: Kattis

Version: Phuoc Hung OJ Extended

Problem Statement

Generate distinct values x1,…,xnx_1,\ldots,x_n from xi=(axi−1+c) mod mx_i=(a x_{i-1}+c)\bmod m using seed x0x_0, which is not part of the array. Ann forgot to sort the generated array and still performs ordinary binary search with the lower midpoint and left/right choices by comparison. Count how many of its own values can be found by this search on the UNSORTED array.

Input

A single line contains n,m,a,c,x0n,m,a,c,x_0 in that order.

Output

Print the count of generated values that remain findable by standard binary search on the unsorted array.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le20; 1≤m,a,c≤231−11\le m,a,c\le2^{31}-1; 0≤x0≤231−10\le x_0\le2^{31}-1; all generated xix_i are pairwise distinct.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le2000; 1≤m,a,c≤231−11\le m,a,c\le2^{31}-1; 0≤x0≤231−10\le x_0\le2^{31}-1; all generated xix_i are pairwise distinct.
  • Subtask 3 (50 points): 1≤n≤10000001\le n\le1000000; 1≤m,a,c≤231−11\le m,a,c\le2^{31}-1; 0≤x0≤231−10\le x_0\le2^{31}-1; all generated xix_i are pairwise distinct.

Examples

Input

5 8 1 3 3

Output

2

Explanation

Using the recurrence yields [6,1,4,7,2][6,1,4,7,2]. Search for 44 succeeds immediately at middle index 22. Search for 77 compares against 44, goes right, then finds 77 at index 33. Search for 66 goes right on 44 and then left on 77, incorrectly missing its actual index 00; similarly 11 and 22 are missed. Thus exactly two values are findable.