分析:枚举序列起点和升降顺序,我写的很暴力,没有什么优化的地方。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <set>
#define FRER() freopen("in.txt","r",stdin)
#define FREW() freopen("out.txt","w",stdout)
#define go int T;cin>>T;for(int kase=1;kase<=T;kase++)
#define debug cout<<"****************"<<endl
#define mod 1000000007
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int> pii;
template <class T> T gcd(T a,T b){return !b?a:gcd(b,a%b);}
const int maxn = 507 , inf = 0x3f3f3f3f;
int n;
void Swap(int i,int j,int *a,int *pos){
swap(a[pos[i]],a[pos[j]]);
swap(pos[j],pos[i]);
}
int a[maxn],b[maxn];
int posa[maxn],posb[maxn];
int main(){
FRER();
FREW();
while(cin>>n&&n){
for(int i=0;i<n;i++){
cin >> a[i];
posa[a[i]] = i;
}
int ans = inf;
for(int k = 1;k<=n;k++){
memcpy(b, a, sizeof(a));
memcpy(posb, posa, sizeof(posa));
int ans1 = 0, ans2 = 0;
if(b[0]!=k){
Swap(b[0], k, b, posb);
ans1++;
}
for(int i=0;i<n;i++){
if(b[i]==n){
if(b[(i+1)%n]!=1){
Swap(b[(i+1)%n], 1, b, posb);
ans1++;
}
}else{
if(b[(i+1)%n]!=b[i]+1){
Swap(b[(i+1)%n], b[i]+1, b, posb);
ans1++;
}
}
}
memcpy(b, a, sizeof(a));
memcpy(posb, posa, sizeof(posa));
if(b[0]!=k){
Swap(b[0], k, b, posb);
ans2++;
}
for(int i=0;i<n;i++){
if(b[i]==1){
if(b[(i+1)%n]!=n){
Swap(b[(i+1)%n], n, b, posb);
ans2++;
}
}else{
if(b[(i+1)%n]!=b[i]-1){
Swap(b[(i+1)%n], b[i]-1, b, posb);
ans2++;
}
}
}
ans = min(ans,min(ans1,ans2));
}
cout<<ans<<endl;
}
}