UVA-331
题意:给出的数据只能相邻2个交换,求经最少次交换使得序列为递增序列的交换方法有多少个。
解题思路:只能相邻两个交换要换到递增顺序的次数是整个串中逆序对的个数 cnt。DFS暴力模拟交换,交换cnt次后,如果序列是递增的,ans++.。最后输出ans。
/*************************************************************************
> File Name: UVA-331.cpp
> Author: Narsh
>
> Created Time: 2016年07月27日 星期三 15时20分59秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int temp[10],n,cnt,ans,num=0;
bool check() {
for (int i = 1; i < n; i++)
if (temp[i] > temp[i+1]) return false;
return true;
}
void dfs(int d) {
if (d == cnt) {
if (check()) ans++;
return ;
}
for (int i = 1; i < n; i++) {
swap(temp[i],temp[i+1]);
dfs(d+1);
swap(temp[i],temp[i+1]);
}
}
int main() {
while (scanf("%d",&n) && n) {
for (int i = 1; i <= n; i++)
scanf("%d",&temp[i]);
cnt=0;
for (int i = 1; i <= n; i++)
for (int j = 1; j < i; j++)
if (temp[j] > temp[i]) cnt++;
ans=0;
if (cnt) dfs(0);
printf("There are %d swap maps for input data set %d.\n",ans,++num);
}
}