在C++遊戲中計算可以減少到零或更小的數字
給定一個包含正數的陣列和兩個整數 A 和 B。兩位玩家正在玩一個遊戲,他們將在陣列中減少數字。玩家 1 可以將陣列的任何元素減少 A,玩家 2 可以將陣列的任何元素增加 B。目標是找到玩家 1 可以減少到 0 或更小的數字的數量。第一位玩家先走。一旦減少到 0 或更小,玩家 2 就不能再考慮這個數字了。
例如
輸入
arr[] = { 1,4,5,2 } A=2, B=3輸出
Count of numbers that can be reduced to zero or less in a game are: 1
解釋
The only number that can be reduced by player 1 is 1 as on first move it will be reduced to −1. Rest all will become greater than A after player 2 increases their value.
輸入
arr[] = { 1,4,5,2 } A=4, B=4輸出
Count of numbers that can be reduced to zero or less in a game are: 2
解釋
On first move player 1 reduces 4 to 0. arr[]= [ 1, 0, 5, 2 ] Player 2 will increase 1 to 4. arr[]= [ 5, 0, 5, 2 ] Player 1 will decrease 2 to −2. Arr[] = [ 5, 0, 5, −2 ]. From now onwards all numbers are greater than A so cannot be reduced by player 1 to 0 or less as player 2 is also increasing them simultaneously.
以下程式中使用的方法如下 −
這種方法首先檢查 A>B。如果是,則在 N 次移動中,A 將把 arr[] 的所有 N 個元素減少到 0 或更小。如果 A<=B,則我們將檢查
所有即使玩家 2 向其新增 B 後也不會大於 A 的數字。假設此計數為 C1。
所有小於 A 且在玩家 2 向其新增 B 後變得大於 A 的數字。假設此計數為 C2。
總數將為 C= C1+ (C2+1)/2。在情況 2 中,只有其中一半會減少到 0 或更小,因為兩位玩家同時增加/減少它們。玩家 2 只能將其中的一半增加到大於 A。與此同時,玩家 1 將把另一半減少到 <=0。
獲取一個包含正數的整數陣列。
獲取兩個變數 A 和 B。
函式 reduced_zero(int arr[], int size, int A, int B) 將返回在遊戲中可以減少到零或更小的數字的數量
將初始計數設定為 0。
將兩個變數 temp_1 和 temp_2 作為臨時計數。
如果 A > B,則返回陣列的長度,即 size。
現在使用 for 迴圈遍歷陣列,對於每個 arr[i],如果元素和 B 的總和 < A,則遞增 temp_1。
對於每個元素 arr[i] <=A,遞增 temp_2。
現在在 for 迴圈結束之後,取 count=temp_1+ (temp_2+1)/2。如公式所示。
返回 count 作為結果。
示例
#include <bits/stdc++.h>
using namespace std;
int reduced_zero(int arr[], int size, int A, int B){
int count = 0;
int temp_1 = 0, temp_2 = 0;
if (A > B){
return size;
}
for(int i = 0; i < size; i++){
if (A >= arr[i] + B){
temp_1++;
}
else if(A >= arr[i]){
temp_2++;
}
}
int temp = (temp_2 + 1) / 2;
count = temp + temp_1;
return count;
}
int main(){
int arr[] = { 3, 3, 1, 2, 4, 7, 1};
int A = 4, B = 1;
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of numbers that can be reduced to zero or less in a game are: "<<reduced_zero(arr, size, A, B);
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Count of numbers that can be reduced to zero or less in a game are: 7
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP