算法二十四:最后胜出队伍

n支队伍比赛,分别编号为0,1,2。。。。n-1,已知它们之间的实力对比关系,

存储在一个二维数组w[n][n]中,w[i][j] 的值代表编号为i,j的队伍中更强的一支。 

所以w[i][j]=i 或者j,现在给出它们的出场顺序,并存储在数组order[n]中,

比如order[n] = {4,3,5,8,1......},那么第一轮比赛就是 4对3, 5对8。.......

胜者晋级,败者淘汰,同一轮淘汰的所有队伍排名不再细分,即可以随便排,

下一轮由上一轮的胜者按照顺序,再依次两两比,比如可能是4对5,直至出现第一名

编程实现,给出二维数组w,一维数组order 和 用于输出比赛名次的数组result[n],

求出result。

从order数组中,每次都选出两支队伍比赛,失败的队伍将退出比赛,所以我们可以用list来存储队伍,每经过一场比赛,将失败的队伍删除,持续这种过程知道最后只剩一支队伍,就是最后获胜的队伍。由于要输出最后比赛的名次,所以可以将每次失败的队伍取出来放到结果中。

 

#include< stdio.h>

#include< list>

#include< iostream>

void raceResult(int** w, int* order, int* result, int n)

{

std::list<int> winer;

 

int count = n;

while(n)

{

winer.push_front(order[--n]);

}

 

int resultNum = count - 1;

int nFirst, nSecond;

int round = 1;

while(winer.size()> 1)

{

//一轮开始

std::cout<<std::endl<<"round "<<round++<<std::endl;

std::list<int>::iterator it = winer.begin();

while (it != winer.end())

{

nFirst = *it;

if (++it == winer.end())

{

//轮空

std::cout<<nFirst<<" rest this round"<<std::endl;

}

else

{

nSecond = *it;

int nWiner = *((int*)w + count * nFirst + nSecond);

if (nWiner  == nFirst)

{

it = winer.erase(it);

result[resultNum--] = nSecond;

std::cout<<nFirst<<" kick out "<<nSecond<<std::endl;

}

else

{

it = winer.erase(--it);

result[resultNum--] = nFirst;

++it;

std::cout<<nSecond<<" kick out "<<nFirst<<std::endl;

}

}

}

}

if (winer.size() == 1)

{

result[0] = winer.front();

}

std::cout<<std::endl<<"final result: ";

int nPlace = 0;

while(nPlace < count)

{

std::cout<<std::endl<<result[nPlace++];

}

}

void test()

{

//team 2>team 1>team 3>team 0>team 4>team 5

int w[6][6] = {

0,1,2,3,0,0,

1,1,2,1,1,1,

2,2,2,2,2,2,

3,1,2,3,3,3,

0,1,2,3,4,5

};

int order[6] = {1,3,4,2,0,5};

int result[6] = {-1};

raceResult((int**)w, order, result, 6);

getchar();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值