问题描述:
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。
算法:利用队列来实现,当队列中元素个数大于1时,则队首两元素出队PK,胜利的那个元素入队,直至队列中只剩一个元素,即为第一名。
代码实现:
#include <iostream>
#include <queue>
using namespace std;
#define TEAM_COUNT 7
void getResult(int w[][TEAM_COUNT], int order[], int result[], int n);
int main(int, char **)
{
//假设胜负关系:6 > 0 > 2 > 3 > 1 > 4 > 5
int w[TEAM_COUNT][TEAM_COUNT] = {
{0, 0, 0, 0, 0, 0, 6},
{0, 1, 2, 3, 1, 1, 6},
{0, 2, 2, 2, 2, 5, 6},
{0, 3, 2, 3, 3, 3, 6},
{0, 1, 2, 3, 4, 4, 6},
{0, 1, 2, 3, 4, 5, 6},
{6, 6, 6, 6, 6, 6, 6}
};
int oreder[TEAM_COUNT] = {0, 1, 2, 3, 4, 5, 6}; //出场顺序
int result[TEAM_COUNT]; //排名
getResult(w, oreder, result, TEAM_COUNT);
//打印排名:注意题目要求,同一轮淘汰的所有队伍排名不再细分,即可以随便排
cout << "排名如下:" << endl;
for (int s = 0; s < TEAM_COUNT; s++)
cout << result[s] << " ";
cout << endl;
system("pause");
return 0;
}
void getResult(int w[][TEAM_COUNT], int order[], int result[], int n)
{
queue<int> qQueue;
for (int i = 0; i < n; i++)
qQueue.push(order[i]);
int firstNo, secondNo;
int winNo;
while (qQueue.size() > 1)
{
firstNo = qQueue.front();
qQueue.pop();
secondNo = qQueue.front();
qQueue.pop();
winNo = w[firstNo][secondNo];
qQueue.push(winNo);
if (firstNo == w[firstNo][secondNo])
result[secondNo] = n;
else
result[firstNo] = n;
n--;
}
result[qQueue.front()] = 1;
}