Algorithm
problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1671
A permutation of n is a bijective function of the initial n natural numbers: 0, 1, . . . , n − 1. A permutation p is called antiarithmetic if there is no subsequence of it forming an arithmetic progression of length bigger than 2, i.e. there are no three indices 0 ≤ i < j < k < n such that (pi , pj , pk) forms an arithmetic progression. For example, the sequence (2, 0, 1, 4, 3) is an antiarithmetic permutation of 5. The sequence (0, 5, 4, 3, 1, 2) is not an antiarithmetic permutation as its first, fifth and sixth term (0, 1, 2) form an arithmetic progression; and so do its second, forth and fifth term (5, 3, 1). Your task is to check whether a given permutation of n is antiarithmetic. Input There are several test cases, followed by a line containing 0. Each test case is a line of the input file containing a natural number 3 ≤ n ≤ 10000 followed by a colon and then followed by n distinct numbers separated by whitespace. All n numbers are natural numbers smaller than n. Output For each test case output one line with ‘yes’ or ‘no’ stating whether the permutation is antiarithmetic or not.
Sample Input 3: 0 2 1 5: 2 0 1 3 4 6: 2 4 3 5 0 1 0
Sample Output yes no yes
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
int n,v;
while(scanf("%d:",&n), n){
vector<int> prev;
unordered_map < int,int> idxMap;
for(int i=0;i < n;i++){
cin >> v;
prev.push_back(v);
idxMap[v] = i;
}
bool hasProgression = false;
for(int i=0;i < n && !hasProgression;i++)
for(int j=i+1;j < n && !hasProgression;j++){
int diff = prev[j] - prev[i];
int nextInt = prev[j] + diff;
if(nextInt > 9 || !idxMap.count(nextInt)) continue;
if(idxMap[nextInt]>j) hasProgression = true;
}
cout << (hasProgression ? "no" : "yes") << endl;
}
}
Copy The Code &
Try With Live Editor
Input
5: 2 0 1 3 4
6: 2 4 3 5 0 1
0
Output
no
yes