-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path957.prison-cells-after-n-days.cpp
113 lines (108 loc) · 2.45 KB
/
957.prison-cells-after-n-days.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* @lc app=leetcode id=957 lang=cpp
*
* [957] Prison Cells After N Days
*
* https://leetcode.com/problems/prison-cells-after-n-days/description/
*
* algorithms
* Medium (37.42%)
* Total Accepted: 20.2K
* Total Submissions: 53.7K
* Testcase Example: '[0,1,0,1,1,0,0,1]\n7'
*
* There are 8 prison cells in a row, and each cell is either occupied or
* vacant.
*
* Each day, whether the cell is occupied or vacant changes according to the
* following rules:
*
*
* If a cell has two adjacent neighbors that are both occupied or both vacant,
* then the cell becomes occupied.
* Otherwise, it becomes vacant.
*
*
* (Note that because the prison is a row, the first and the last cells in the
* row can't have two adjacent neighbors.)
*
* We describe the current state of the prison in the following way: cells[i]
* == 1 if the i-th cell is occupied, else cells[i] == 0.
*
* Given the initial state of the prison, return the state of the prison after
* N days (and N such changes described above.)
*
*
*
*
*
*
*
*
*
* Example 1:
*
*
* Input: cells = [0,1,0,1,1,0,0,1], N = 7
* Output: [0,0,1,1,0,0,0,0]
* Explanation:
* The following table summarizes the state of the prison on each day:
* Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
* Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
* Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
* Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
* Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
* Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
* Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
* Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
*
*
*
*
* Example 2:
*
*
* Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
* Output: [0,0,1,1,1,1,1,0]
*
*
*
*
* Note:
*
*
* cells.length == 8
* cells[i] is in {0, 1}
* 1 <= N <= 10^9
*
*
*
*
*/
class Solution {
public:
void step(vector<int>& x){
vector<int> next(8, 0);
for(int j=1; j<7; j++)
next[j] = !(x[j-1]^x[j+1]);
x = next;
}
vector<int> prisonAfterNDays(vector<int>& x, int N) {
// convert 1st state as it is different from other states
// by ability to have 1 at first and last position
step(x);
N--;
vector<int> nextt = x;
// find after how many days the states repeat
int i;
for(i=1; i<=(1<<8); i++){
step(x);
if(x == nextt)
break;
}
N %= i; // after %, N <= 256
for(i=0; i<N; i++)
step(x);
return x;
}
};