#include void shiftk(int *a, int n, int k); int gcd(int x, int y); int main() { FILE* in = fopen("input.txt", "r"); if (in == NULL) { perror("Cannot open input file"); return -1; } int x; int n = 0; while (fscanf(in, "%d", &x) == 1) { ++n; } fseek(in, 0, SEEK_SET); if (n == 0) { fprintf(stderr, "Empty input file.\n"); return -1; } --n; int *a = NULL; if (n > 0) a = new int[n]; int k; if (fscanf(in, "%d", &k) < 1) { fprintf(stderr, "Incorrect input file.\n"); return -1; } int m = 0; for (int i = 0; i < n; ++i) { if (fscanf(in, "%d", &(a[i])) == 1) { ++m; } } fclose(in); shiftk(a, m, k); FILE* out = fopen("output.txt", "w"); if (in == NULL) { perror("Cannot open output file"); return -1; } for (int i = 0; i < m; ++i) { if (i > 0) { if (i % 10 == 0) fprintf(out, "\n"); else fprintf(out, " "); } fprintf(out, "%d", a[i]); } fprintf(out, "\n"); fclose(out); return 0; } void shiftk(int *a, int n, int k) { if (n <= 1) // Degenerated case return; // Reduce k to the interval 0..n-1 // using the periodicity k %= n; if (k == 0) return; if (k < 0) // Shift to the left on k k += n; // == shift to the right on n-k int i = 0; // Index of the first element of orbit int nod = gcd(n, k); while (i < nod) { // Loop for each orbit // i is the first element of orbit int j = i-k; // j is the last element of orbit if (j < 0) j += n; int x = a[j]; // Save the value of the last element of orbit while (j != i) { // Loop for each element j of orbit int l = j-k; // l is the previous element to j if (l < 0) l += n; a[j] = a[l]; // copy previous element to current j = l; // go to the previous element } a[i] = x; // copy the last element of orbit to the first ++i; // go to the next orbit } } int gcd(int x, int y) { while (y != 0) { int r = x % y; x = y; y = r; } return x; }