题目链接:http://zhedahht.blog.163.com/blog/static/254111742007289205219/
一种变形,我的代码:
#include <stdio.h>
#include <stdlib.h>
#include<memory.h>
#include<iostream>
#include<vector>
#include<set>
#include<iterator>
using namespace std;
int gcd(int a,int b) {
return b?gcd(b,a%b):a;
}
void rotate_cycle(int* data,int first,int last,int init,int shift) {
int val=data[init];
int i=init;
int j=init+shift;
while(j!=init) {
data[i]=data[j];
i=j;
if(j+shift<last) {
j=j+shift;
} else {
j=first+(shift-(last-j));
}
}
data[i]=val;
}
void rotate(int* data,int len,int pivot) {
int n=gcd(pivot,len);
while(n--)
rotate_cycle(data,0,len,n,pivot);
}
int main() {
int data[]= {1,2,3,4,5,6,7};
rotate(data,7,4);
copy(data,data+7,ostream_iterator<int>(cout," "));
return 0;
}