UVa:331 Mapping the Swaps

冒泡每次交换的都是相邻的两个,按照这个。首先进行全排列,再从最小序列开始,每次交换两个,直到交换到最终序列。可行的数目就是答案。

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#define MAXN 205
#define MOD 1000000007
#define INF 2139062143
#define ll long long
using namespace std;
int n,N,ans;
vector<int> vec[MAXN],st,ed;
bool Check(vector<int> a,vector<int> b)
{
    int cnt=0,x,y;
    for(int i=0; i<a.size(); ++i)
    {
        if(a[i]!=b[i])
        {
            cnt++;
            if(cnt>2) return false;
            if(cnt==1) x=i;
            else y=i;
        }
    }
    if(x+1==y) return true;
    else return false;
}
void dfs(int num)
{
    for(int i=num+1; i<N; ++i)
        if(Check(vec[num],vec[i]))
        {
            if(vec[i]==ed) ans++;
            else dfs(i);
        }
}
void Init()
{
    st.clear();
    ed.clear();
}
int main()
{
    int kase=0;
    while(scanf("%d",&n)&&n)
    {
        Init();
        for(int i=0; i<n; ++i)
        {
            int temp;
            scanf("%d",&temp);
            ed.push_back(temp);
            st.push_back(temp);
        }
        sort(st.begin(),st.end());
        N=0;
        do
        {
            vec[N++]=st;
            if(st==ed) break;
        }
        while(next_permutation(st.begin(),st.end()));
        ans=0;
        dfs(0);
        printf("There are %d swap maps for input data set %d.\n",ans,++kase);
    }
    return 0;
}


 

你可能感兴趣的:(搜索,全排列)