k 天后活躍和非活躍單元格?
這裡我們將看到一個有趣的問題。假設給定一個大小為 n 的二進位制陣列。這裡 n > 3。真值或 1 值表示活動狀態,而 0 或假值表示非活動狀態。還給定另一個數字 k。我們必須找到 k 天后的活躍或非活躍單元格。每天,如果第 i 個單元格的左右單元格不相同,則該單元格將處於活動狀態;如果相同,則該單元格將處於非活動狀態。最左側和最右側的單元格之前和之後沒有單元格。因此,最左側和最右側的單元格始終為 0。
讓我們看一個例子來了解一下。假設一個數組是這樣的:{0, 1, 0, 1, 0, 1, 0, 1},並且 k 的值為 3。讓我們看看它每天是如何變化的。
- 1 天后,陣列將變為 {1, 0, 0, 0, 0, 0, 0, 0}
- 2 天后,陣列將變為 {0, 1, 0, 0, 0, 0, 0, 0}
- 3 天后,陣列將變為 {1, 0, 1, 0, 0, 0, 0, 0}
所以有 2 個活躍單元格和 6 個非活躍單元格。
演算法
activeCellKdays(arr, n, k)
begin make a copy of arr into temp for i in range 1 to k, do temp[0] := 0 XOR arr[1] temp[n-1] := 0 XOR arr[n-2] for each cell i from 1 to n-2, do temp[i] := arr[i-1] XOR arr[i+1] done copy temp to arr for next iteration done count number of 1s as active, and number of 0s as inactive, then return the values. end
示例
#include <iostream>
using namespace std;
void activeCellKdays(bool arr[], int n, int k) {
bool temp[n]; //temp is holding the copy of the arr
for (int i=0; i<n ; i++)
temp[i] = arr[i];
for(int i = 0; i<k; i++){
temp[0] = 0^arr[1]; //set value for left cell
temp[n-1] = 0^arr[n-2]; //set value for right cell
for (int i=1; i<=n-2; i++) //for all intermediate cell if left and
right are not same, put 1
temp[i] = arr[i-1] ^ arr[i+1];
for (int i=0; i<n; i++)
arr[i] = temp[i]; //copy back the temp to arr for the next iteration
}
int active = 0, inactive = 0;
for (int i=0; i<n; i++)
if (arr[i])
active++;
else
inactive++;
cout << "Active Cells = "<< active <<", Inactive Cells = " << inactive;
}
main() {
bool arr[] = {0, 1, 0, 1, 0, 1, 0, 1};
int k = 3;
int n = sizeof(arr)/sizeof(arr[0]);
activeCellKdays(arr, n, k);
}輸出
Active Cells = 2, Inactive Cells = 6
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP