Jeff and Periods
Description
One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:
- x occurs in sequence a.
- Consider all positions of numbers x in the sequence a (such i, that ai = x). These numbers, sorted in the increasing order, must form an arithmetic progression.
Help Jeff, find all x that meet the problem conditions.
Input
The first line contains integer n(1 ≤ n ≤ 105). The next line contains integers a1, a2, ..., an(1 ≤ ai ≤ 105). The numbers are separated by spaces.
Output
In the first line print integer t — the number of valid x. On each of the next t lines print two integers x and px, where x is current suitable value, px is the common difference between numbers in the progression (if x occurs exactly once in the sequence, px must equal 0). Print the pairs in the order of increasing x.
Sample Input
1 #include<stdio.h> 2 #include<string.h> 3 4 #define maxn 100005 5 6 int step[maxn]; 7 int first[maxn]; 8 int last[maxn]; 9 10 int main() 11 { 12 int i, n, a, c = 0; 13 memset(first, -1, sizeof(first)); 14 memset(last, -1, sizeof(last)); 15 memset(step, 0, sizeof(step)); 16 while (scanf("%d", &n) != EOF) 17 { 18 for (i = 0; i < n; i++) 19 { 20 scanf("%d", &a); 21 if (first[a] == -1) //取a的值为数组下标,a为元素的值 22 { 23 first[a] = i; //first[a]为【第一次】出现 之前未出现的元素 的位置 24 c++; //只要是第一次出现此数,就计数 25 } 26 else 27 { 28 if (step[a] == 0) 29 { 30 step[a] = i - first[a]; //【第一次】出现 某个元素 据第一个与它值相同的元素的步数(即公差) 31 } 32 else if (step[a] > 0 && (i - last[a]) != step[a]) //如果之后出现的元素 据 上一个与它相同的元素的步数 != 公差 33 { 34 step[a] = -1; //则置为-1,不输出此元素 35 c--; //不计入此数 36 } 37 } 38 last[a] = i; //记录这次该元素的位置,以便下次此值再出现时比较步数与公差 39 } 40 printf("%d ", c); 41 for (i = 1; i <= maxn - 1; i++) 42 { 43 if (first[i] >= 0) 44 { 45 if (step[i] >= 0) //对于只出现一次的数,step[i] = 0,也会输出 46 { 47 printf("%d %d ", i, step[i]); //i为元素a的值,step[i]为公差 48 } 49 } 50 } 51 } 52 return 0; 53 }