B Table Tennis
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 1012) — the number of people and the number of wins.
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ n) — powers of the player. It’s guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer — power of the winner.
Examples
inputCopy
2 2
1 2
outputCopy
2
inputCopy
4 2
3 1 2 4
outputCopy
3
inputCopy
6 2
6 5 3 1 2 4
outputCopy
6
inputCopy
2 10000000000
2 1
outputCopy
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.
题意:
题目大概意思是n个人打乒乓球比赛,给出n个数代表每个人的实力,也是比赛最开始的顺序,一开始,按顺序依次两两对打,输的人就进入输的队伍的最后面,赢的人按顺序继续打比赛,当有一个人赢了连赢k局,就输出这个人的实力。
题解:
从第一个数开始,把它的后面一个数比较,如果它比后一个数大的话就和它和后一个数交换,计数器加一;如果这个数比后一个数小,就不用交换位置,而是把后一个数来进行后面的交换,计数器初始化,但是这里初始化要初始化成1!!!,因为后面这个数已经赢了前一个数一次了(被这个坑了好久);这个过程有点像冒泡。如果遍历到了数组的末尾,就从数组的第一位接着比较,注意n最大只有500,k却有10的12次方,可以一开始就比较k和n,如果k>=n-1的话就直接输出数组中的最大值就行了,或者当计数器到n-1是就结束比较,输出此时的值就是答案了
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
long long k; //k最大是10的12次方,所以要用long long
int n;
while(cin >> n >> k){
int a[510];
for(int i = 0;i < n;i++)
cin >> a[i];
int j = 0,mark = 0,count = 0;
while(true){
int i = j + 1;
while(1){
if(count >= k || count >= n - 1){ //大于k或者大于n-1就break输出答案
mark = 1;
break;
}
if(i == n) //超出数组时把 i 赋值成0,继续比较
i = 0;
if(a[j] > a[i]){ //a[j] > a[i] 交换位置,j 的值也要变成 i
int t = a[j];
a[j] = a[i];
a[i] = t;
j = i;
count++;
}
else{ //a[j] < a[i],j 赋值成 i 就行
j = i;
count = 1; //初始化成 1 因为这时候已经赢了一次了
break;
}
i++;
}
if(mark)
break;
}
cout << a[j] << endl;
}
return 0;
}