/*
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;
}
}
1006.Team Rankings 栈与回溯 简单 5!搜索
最新推荐文章于 2016-11-23 19:40:00 发布