Sei sulla pagina 1di 2

// Comparing equal vectors

vector<int> v1{ 3, 1, 2,3 };


vector<int> v2{ 3, 1, 2, 3 };
(v1 == v2) ? cout << "Equal\n" : cout << "Not Equal\n";

957. Prison Cells After N Days-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.
Given the initial state of the prison, return the state of the prison after N days(and N such changes
described above.)
Sol- Because there are at most 256(8 digit no) possible states for the prison, eventually the states repeat into a cycle rather
quickly. We can keep track of when the states repeat to find the period t of this cycle, and skip days in multiples of t.

Algorithm

vector<int> prisonAfterNDays(vector<int>& cells, int N) {


int n = cells.size(), cycle = 0;
vector<int> cur(n, 0), direct;
while (N-- > 0) {
for (int i = 1; i < n - 1; ++i) cur[i] = cells[i - 1] == cells[i + 1];
if (direct.empty()) direct = cur;
else if (direct == cur) N %= cycle;
++cycle;
cells = cur;
}
return cur;
}

vector<int> prisonAfterNDays(vector<int>& c, int N) {


vector<int> f_c, next_c(c.size(), 0);
for (int cycle = 0; N-- > 0; c = next_c, ++cycle) {
for (auto i = 1; i < c.size() - 1; ++i) next_c[i] = c[i - 1] == c[i + 1];
if (cycle == 0) f_c = next_c;
else if (next_c == f_c) N %= cycle;
}
return c;
}

472. Concatenated Words-


Given a list of words(without duplicates), please write a program that returns all concatenated words in the
given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the
given array.
Input: ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]
Output : ["catsdogcats", "dogcatsdog", "ratcatdogcat"]
Explanation : "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
#include <sstream>
vector<string> split(string s, char delim) {
vector<string> result;
stringstream ss(s);
string item;

while (getline(ss, item, delim)) {


result.push_back(item);
}

return result;
}

Potrebbero piacerti anche