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