大意;求在最小的交换次数的情况下使得序列升序排列的方案数。
思路:冒泡排序对应最小交换数,然后回溯。
CODE:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
int ans;
int n;
int a[1001];
int check(int *a)
{
for(int i = 0; i < n-1; i++)
{
if(a[i] > a[i+1]) return 0;
}
return 1;
}
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void dfs(int *a)
{
if(check(a))
{
ans++;
return ;
}
else for(int i = 0; i < n-1; i++)
{
if(a[i] > a[i+1])
{
swap(a[i], a[i+1]);
dfs(a);
swap(a[i], a[i+1]);
}
}
}
int main()
{
int times = 0;
while(~scanf("%d", &n) && n)
{
ans = 0;
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
if(!check(a))
{
dfs(a);
}
printf("There are %d swap maps for input data set %d.\n", ans, ++times);
}
return 0;
}
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
int ans;
int n;
int a[1001];
int check(int *a)
{
for(int i = 0; i < n-1; i++)
{
if(a[i] > a[i+1]) return 0;
}
return 1;
}
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void dfs(int *a)
{
if(check(a))
{
ans++;
return ;
}
else for(int i = 0; i < n-1; i++)
{
if(a[i] > a[i+1])
{
swap(a[i], a[i+1]);
dfs(a);
swap(a[i], a[i+1]);
}
}
}
int main()
{
int times = 0;
while(~scanf("%d", &n) && n)
{
ans = 0;
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
if(!check(a))
{
dfs(a);
}
printf("There are %d swap maps for input data set %d.\n", ans, ++times);
}
return 0;
}