สมมติว่าเรามีอาร์เรย์ที่มี n องค์ประกอบตั้งแต่ 1 ถึง n ตามลำดับที่สับเปลี่ยน ให้จำนวนเต็ม K อีกตัวหนึ่ง มีคน N ยืนต่อแถวเล่นแบดมินตัน ผู้เล่นสองคนแรกจะไปเล่นแล้วผู้แพ้จะไปที่ท้ายคิว ผู้ชนะจะเล่นกับคนต่อไปจากคิวเป็นต้น พวกเขาจะเล่นจนกว่าจะมีคนชนะ K ครั้งติดต่อกัน จากนั้นผู้เล่นคนนั้นจะกลายเป็นผู้ชนะ
หากคิวเป็นแบบ [2, 1, 3, 4, 5] และ K =2 ผลลัพธ์จะเป็น 5 ตอนนี้ดูคำอธิบาย -
(2, 1) เล่น, 2 ชนะ, ดังนั้น 1 จะถูกเพิ่มเข้าไปในคิว, คิวเป็นเหมือน [3, 4, 5, 1] (2, 3) เล่น, 3 ชนะ, ดังนั้น 2 จะถูกเพิ่มเข้าไปในคิว, คิวเป็นเหมือน [4, 5, 1, 2] (3, 4) เล่น 4 ชนะดังนั้น 3 จะถูกเพิ่มเข้าไปในคิวคิวเป็นเหมือน [5, 1, 2, 3] (4, 5) เล่น 5 ชนะ ดังนั้น 4 จะถูกเพิ่มเข้าไปในคิว คิวเป็นเหมือน [1, 2, 3, 4] (5, 1) เล่น, 5 ชนะ ดังนั้น 3 จะถูกเพิ่มเข้าไปในคิว คิวเป็นเหมือน [2, 3 , 4, 1]
(2, 1) เล่น, 2 ชนะ, ดังนั้น 1 จะถูกเพิ่มเข้าไปในคิว, คิวเป็นเหมือน [3, 4, 5, 1]
(2, 3) เล่น 3 ชนะดังนั้น 2 จะถูกเพิ่มเข้าไปในคิวคิวเป็นเหมือน [4, 5, 1, 2]
(3, 4) เล่น 4 ชนะดังนั้น 3 จะถูกเพิ่มเข้าไปในคิวคิวเป็นเหมือน [5, 1, 2, 3]
(4, 5) เล่น 5 ชนะดังนั้น 4 จะถูกเพิ่มเข้าไปในคิวคิวเป็นเหมือน [1, 2, 3, 4]
(5, 1) เล่น, 5 ชนะ, ดังนั้น 3 จะถูกเพิ่มเข้าไปในคิว, คิวเป็นเหมือน [2, 3, 4, 1]
เมื่อชนะ 5 นัดติดต่อกัน 2 นัด จากนั้นเอาท์พุตคือ 5.
อัลกอริทึม
ผู้ชนะ(arr, n, k)
Begin if k >= n-1, then return n best_player := 0 win_count := 0 for each element e in arr, do if e > best_player, then best_player := e if e is 0th element, then win_count := 1 end if else increase win_count by 1 end if if win_count >= k, then return best player done return best player End
ตัวอย่าง
#include <iostream>
using namespace std;
int winner(int arr[], int n, int k) {
if (k >= n - 1) //if K exceeds the array size, then return n
return n;
int best_player = 0, win_count = 0; //initially best player and win count is not set
for (int i = 0; i < n; i++) { //for each member of the array
if (arr[i] > best_player) { //when arr[i] is better than the best one, update best
best_player = arr[i];
if (i) //if i is not the 0th element, set win_count as 1
win_count = 1;
}else //otherwise increase win count
win_count += 1;
if (win_count >= k) //if the win count is k or more than k, then we have got result
return best_player;
}
return best_player; //otherwise max element will be winner.
}
main() {
int arr[] = { 3, 1, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << winner(arr, n, k);
} ผลลัพธ์
3