1006.Team Rankings 栈与回溯 简单 5!搜索

/*
1006.Team Rankings 栈与回溯 简单  5!搜索
题目大意:
        对于两个排列p, q,定义 distance( p, q )为在p, q中出现的相对次序不同的元素的对数。相当于以p为基准,求q的逆序数。
        给出n个5元排列,构造一个排列,使得该排列对n个排列的distance之和最小。
        n<=100
解题思路:
        枚举所有5元排列,与n个排列一一比较5个元素之间顺序并累加;
        枚举方法可用递归。

*/
#include <iostream>
#include <string>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;



//1.重点:用于存储标准排列的值,务必熟悉map 
map<char,int> m ;
string str ;

//2.重点:返回比较排列与标准排列的距离值 
int calculate(string temp)
{
    int sum = 0 ;
    for(int i = 0 ;i < 4 ; i++)
    {
        for(int j = i + 1 ; j < 5 ; j ++)
        {
            if( m[temp[i]] > m[temp[j]]) 
                sum ++ ;
        }
    }
    return sum ;
}


int main()
{
    int n ;
    while(1 )
    {
        cin >> n;
        if(n == 0)
           break;
        str = "ABCDE" ;
        string min_str ;
        int min_count = 999999999 ;

        string temp[105] ;
        for(int i = 0 ; i < n ; i ++)
        {
            cin >> temp[i] ;
        }

        do
        {
            for(int i = 0 ;i  < 5 ; i ++)
            {
                m[str[i]] = i ;
            }

            int ans = 0 ;
            for(int  i = 0 ; i < n ; i ++)
            {
                ans += calculate(temp[i]) ;
            }
            
            if(min_count > ans )
            {
                min_count = ans ;
                min_str = str ;
            }
        }while(next_permutation(str.begin() ,str.begin() + 5)) ;  //重点3:next_permutation函数生成下一个较大的排列成功则返回true
        //The next_permutation() function attempts to transform the given range of elements [start,end) 
        //into the next lexicographically greater permutation of elements. If it succeeds, it returns true, 
        //otherwise, it returns false. 
        //#include <algorithm>
        //next_permutation(str.begin() ,str.end());
  
        cout << min_str << " is the median ranking with value "<< min_count  << "."<<endl;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值