求出result。
思路:看到这道题目的时候,我第一个想法就是这道题目还是比较简单的。因为初看起来,他的思路比较明确,只要按照题目中说的顺序,按部就班的就可以得到结果。仅仅需要自己选择比较合适的数据结构来存放排序过程中的状态量即可。因为题目里面没有给定数据,所以,我就采用july大神答案中的数据写了下程序。主要的思路是用队列存放将要参加比赛的队伍,然后,每次从队中取出两个,进行比较,赢的继续压入队中,输的压到栈中。每轮结尾都要在队中压入标志位-1,这是因为有可能每轮在最后剩一个队可能本轮轮空。思路比较正常。
贴上代码:
/*=================================================================*\36.引用自网友:longzuo(运算)谷歌笔试: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。\*=================================================================*/#include#include #include using namespace std;bool raceResult(int (*w)[6],int *order,int *result,int n){ queue q; stack s; for(int i = 0 ; i < n ; ++i){ q.push(order[i]); } q.push(-1);//一轮的标志位 //cout << q.size() << endl;//输出长度 while(q.size() > 2){ int firstTeam = q.front(); q.pop(); int secondTeam = q.front();//从出场顺序队列中取出两队并将第队出队 if(-1 == firstTeam || -1 == secondTeam){ if(-1 == firstTeam){ q.push(-1); }else{ q.pop(); q.push(firstTeam); q.push(-1); } }else{ int temp = w[firstTeam][secondTeam]; if(temp == firstTeam){ q.pop(); q.push(firstTeam); s.push(secondTeam); }else{ q.pop(); q.push(secondTeam); s.push(firstTeam); } } } if(2 == q.size()){ if(-1 == q.front()){ q.pop(); s.push(q.front()); }else{ s.push(q.front()); } } for(int i = 0 ; i < n ; ++i){ result[i] = s.top(); s.pop(); } return true;}int main(){ //team2>team1>team3>team0>team4>team5 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,4, 0,1,2,3,4,5 }; int order[6]={1,3,4,2,0,5}; int result[6]= {-1}; raceResult(w,order,result,6); for(int i = 0 ; i < 6 ; ++i){ cout << result[i] << " "; } cout << endl; system("pause"); return 1;}