There is a task, the essence of which boils down to checking the possibility of sorting a certain set of numbers. If sorting is possible then output YES, otherwise NO.
k-sort
This year, Grisha entered the University of IT. At the University of IT a lot of new items, and not very interesting. Grisha especially likes the subject "Algorithms and Data Structures". In the last lecture, sorting algorithms were told. Grisha is a very ambitious young man and wants to invent his own algorithm, which will later be named after his beloved grandfather. Inspired by the reading of Knuth’s multi-volume, Grisha decided to upgrade some existing algorithm for sorting natural numbers, imposing the following restriction. Any two elements can be interchanged only if they are comparable in magnitude to some natural number k, that is, they give the same residues when divided by k. But all innovative methods require verification, so Grisha turned to you for help!
Check if the new version of the algorithm can sort the given array of natural numbers.
Input data
The first line of the input file contains two numbers n (1 ≤ n ≤ 1000) and k (1 ≤ k ≤ 10 9 ) - the number of elements in the array and the number modulo which the elements of the array are compared.
The second line of the input file contains n integers ai - array elements (1 ≤ ai ≤ 10 9 ).
Output
In the output file output YES, if the algorithm can sort the specified array and NO - otherwise.
Actually, this is the text of the problem itself. Test data are as follows:
5 2 1 2 3 4 5 - результат YES 3 2 2 3 1 - результат NO.
My algorithm for solving the problem is as follows
#include <iostream> #include <ctype.h> using namespace std; int main() { int n = 0; int k = 0; int *array; cin >> n; if (n == 1) { cout << "YES" << endl; return 0; } cin >> k; if (k == 1) { cout << "YES" << endl; return 0; } array = new int[n]; for (int i = 0; i < n; ++i) { cin >> array[i]; } int afterTemp = 0; int beforeTemp = 0; afterTemp = array[0] % k; beforeTemp = array[1] % k; bool switchMod = true; for (int i = 2; i < n; ++i) { if (switchMod) { if (array[i] % k == afterTemp) { switchMod = false; } else { cout << "NO" << endl; return 0; } } else { if (array[i] % k == beforeTemp) { switchMod = true; } else { cout << "NO" << endl; return 0; } } } cout << "YES" << endl; return 0; }
In the testing system I pass only half of the correct answers (53%). If anyone has any ideas that I could miss, please tell me.