UVA 331 Mapping the Swaps

本文介绍了解决UVA-331问题的方法,该问题要求通过最少次数的相邻元素交换使序列变为递增顺序,并计算所有可能的交换方案数量。采用深度优先搜索(DFS)模拟交换过程,统计序列中逆序对的数量作为交换次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值