Codeforce - 352B - Jeff and Periods

B. Jeff and Periods
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Examples
input
1
2
output
1
2 0
input
8
1 2 1 3 1 2 1 5
output
4
1 2
2 4
3 0
5 0
Note
In the first test 2 occurs exactly once in the sequence, ergo p2 = 0.

題意:給出 n 個數,求兩個相同數字之間的間隔是否成等差數列,若其位置成等差,則輸出其間隔,若數字只出現了一次則輸出 0.

思路:注意比較本次間隔與上兩次間隔是否相等。
需要三個數組來記錄, first 可以用於記錄當前的座標, step 可以記錄兩最近的相同數字之間的間隔, last 可以放置上一個座標。

AC代碼:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    int n;cin>>n;
    int a[n+5],first[100001],step[100001],last[100001];
    memset (first,-1,sizeof(first));
    memset (step,0,sizeof(step));
    memset (last ,-1,sizeof (last));
    int c=0;
    for (int i=0;i<n;i++)
    {
        int a;cin>>a;
        if (first[a]==-1)
        {
            first[a]=i;
            c++;
        }
        else
        {
            if (step[a]==0) step[a]=i-first[a];
            else if (step[a]>0 && (i-last[a] != step[a]))
            {
                step[a]=-1;
                c--;
            }
        }
        last[a]=i;
    }
    cout<<c<<endl;
    for (int i=1;i<=100000;i++)
    {
        if (first[i]>=0 && step[i]>=0)
            cout<<i<<" "<<step[i]<<endl;
    }
}
發佈了47 篇原創文章 · 獲贊 28 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章