sicily 1006.Team Rankings


//sicily 1006.Team Rankings,1.求一个字符串相对于另一个字符串的逆序对数 2.给定n个字符串,找出一个字符串,使这个字符串与这n个字符串的逆序对数最小
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

string ranks[10005];//存储用户输入的n组数组
bool used[10000];//在递归ABCDE所能组成的所有字符串中用到,用来标识一个字符是否已经使用

//char result[10000];//符合条件的字符串
int value;//符合条件的字符串与其他n对字符串的最小逆序对

int distance(string a,char b[])
{
    int posa[1000],posb[1000];//记录字符串中每个字符对应的位置
    int count = 0;
    for(int i = 0;i < 5;i++)
    {
        //printf("%c",a[i]);
        posa[a[i]] = i;
        posb[b[i]] = i;
    }
    for(char c1 = 'A';c1 <= 'E';c1++)
        for(char c2 = c1 + 1;c2 <= 'E';c2++)
            if((posa[c1] - posa[c2])*(posb[c1] - posb[c2]) < 0)//是逆序对
                count++;
    return count;
}

void cal(char rank[],int n,char result[])
{
    int count = 0,temper;
    for(int i = 0;i < n;i++)
        count = count + distance(ranks[i],rank);
    if(count < value)
    {
        value = count;
        strcpy(result,rank);
    }
}


void dfs(char rank[],int pos,int n,char result[])//求A,B,C,D,E所能组成的所有字符串
{
    if(pos == 5)
    {
        rank[5] = '\0';
        cal(rank,n,result);
        return;
    }
    for(char c = 'A';c <= 'E';c++)
        if(used[c] == false)
        {
            used[c] = true;
            rank[pos] = c;
            dfs(rank,pos + 1,n,result);
            used[c] = false;
        }
}

int main()
{
    int n;
   
    while(scanf("%d",&n) && n != 0)
    {
        for(int i = 0;i < n;i++)
        {
            cin >> ranks[i];
        }
        char rank[10000] = {""};
        char result[10000] = {""};
        //int value = 10000;
        value = 10000;
        //result = {""};
        dfs(rank,0,n,result);
        printf("%s is the median ranking with value %d.\n",result,value);
        //cout << result + " is the median ranking with value " + value + "." << endl;
    }
    return 0;
}                                 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值