## Saturday, July 30, 2016

### HackerRank color grid

https://github.com/shawnfan/LintCode/blob/master/Java/ColorGrid.java
https://www.hackerrank.com/contests/ioi-2014-practice-contest-1/challenges/color-grid-ioi14
You are given an N×NN×N grid. Each cell has the color white (color 0) in the beginning.
Each row and column has a certain color associated with it. Filling a row or column with a new color VV means changing all the cells of that row or column to VV (thus overriding the previous colors of the cells).
Now, given a sequence of PP such operations, calculate the sum of the colors in the final grid.
For simplicity, the colors will be positive integers whose values will be most 109109.
Input Format
The first line of input contains two integers NN and PP separated by a space.
The next PP lines each contain a filling operation. There are two types of filling operations.
ROW I V which means "fill row II with color VV".
COL I V which means "fill column II with color VV".
Output Format
Output one line containing exactly one integer which is the sum of the colors in the final grid.
Constraints
1≤N≤60001≤N≤6000
1≤P≤4000001≤P≤400000
1≤I≤N1≤I≤N
1≤V≤1091≤V≤109
Sample Input
5 4
COL 1 6
COL 4 11
ROW 3 9
COL 1 24
Sample Output
200
Explanation
There are four operations. After the second operation, the grid looks like
6  0  0 11  0
6  0  0 11  0
6  0  0 11  0
6  0  0 11  0
6  0  0 11  0
After the third operation (ROW 3 9), the third row was colored with 9, overriding any previous color in the cells.
6  0  0 11  0
6  0  0 11  0
9  9  9  9  9
6  0  0 11  0
6  0  0 11  0
After the fourth operation (COL 1 24), the grid becomes:
24  0  0 11  0
24  0  0 11  0
24  9  9  9  9
24  0  0 11  0
24  0  0 11  0
The sum of the colors in this grid is 200.

https://www.hackerrank.com/contests/ioi-2014-practice-contest-1/challenges/color-grid-ioi14/editorial
Note that simply simulating the  operations will take  time. This means that when  and , then this solution will take at least 2.4 billion operations. This is too slow to pass the time limit for this problem.

### Fast solution 1

Consider a particular row (or column). Suppose that there are two operations that write a color at that row (or column). Suppose that the first operation is done at time  and writes color , and the second operation is done at time  and operation  (where ).

Notice that the first operation is irrelevant, because you know that you will do another operation at that row (or column) at a later time, i.e. whatever you write at  will surely be overwritten at time . Therefore, simulating the first operation is not necessary.

What does this mean? This means that for every row/column, you should only simulate the latest operations that write to that row/column. This is done by first taking all operations, and taking note of the latest time of an operation per row and column, and finally simulating only the operations that are the last in their corresponding row/column.

Since there are  rows and  columns, there are at most  rows to simulate. Since each simulated operation costs  time, this algorithm takes  time (the  appears because we still have to read the operations). If  is less than 40 million, so this passes the time limit well :)

### Fast solution 2

There's an alternative  time solution. This involves reversing the order of operations, but instead of overriding the cells, we never write on the cells that have been written on already. Additionally, we also keep track whether a row/column has already been operated on already, because it is not really useful to simulate an operation on such a row/column. Thus, after simulating an operation, we mark that row or column as used ordeleted.

Since each row or column will be operated on at most once, this algorithm also takes  time.

### Even faster solution!

The solutions above will pass the time limit well. However, a simple modification of the second fast solution results in an even faster solution that will enable us to calculate the answer even if  had a much higher bound :)

The idea is this: at any point during simulating the operations in reverse, you know exactly how many cells in each row and column are alive. This is because after every row operation, the number of 'alive' rows is reduced by 1, and the same is true after a column operation.

Therefore, for a particular painting with color , we know exactly how many times the color  will be painted on the grid! This saves us from actually simulating the painting at all. There's no need to create a grid, just keep track of the number of alive rows and columns after every operation!

Since there is no more simulation, this algorithm now runs in  time! This means that the algorithm will still pass the time limit even though the upper bound for  were, say,
int alive_row[411111];
int alive_col[411111];
int ts[411111];
int is[411111];
int vs[411111];
char cmd[111];
int main() {
// take the input
int n, p, i, v;
scanf("%d%d", &n, &p);
for (int i = 1; i <= n; i++) {
alive_row[i] = alive_col[i] = 1;
}
for (int k = 0; k < p; k++) {
scanf("%s%d%d", cmd, &i, &v);
ts[k] = *cmd == 'R';
is[k] = i;
vs[k] = v;
}

// here, 'rows' is the number of undeleted rows left
//       'cols' is the number of undeleted columns left
//       'sum' is the current sum
ll rows = n, cols = n, sum = 0;
for (int k = p - 1; k >= 0; k--) {
int i = is[k], v = vs[k];
if (ts[k]) { // this is a row update
if (alive_row[i]) {
alive_row[i] = 0;
sum += cols * v;
rows--;
}
} else { // this is a column update
if (alive_col[i]) {
alive_col[i] = 0;
sum += rows * v;
cols--;
}
}
}

// print the sum
printf("%lld\n", sum);
}

### Even, even faster solution!

Finally, this algorithm can be done in  time, by using a data structure called a set. Keep track of two sets called deleted_rows and deleted_cols, and any time a row or column is operated on, insert it into the corresponding set.

If the implementation of the set data structure uses hashing, then inserting in a set and checking if a value is in a set should run in  time! For more information on hash-based sets, and sets in general, see Set (abstract data type).

Note that the complexity  is independent of . This means that our algorithm will still work even if 's bound was even higher, say, , where we won't even have enough memory to allocate  bytes!
unordered_set<int> deleted_rows;
unordered_set<int> deleted_cols;
int ts[411111];
int is[411111];
int vs[411111];
char cmd[111];
int main() {
// take the input
ll n;
int p, i, v;
scanf("%lld%d", &n, &p);
for (int k = 0; k < p; k++) {
scanf("%s%d%d", cmd, &i, &v);
ts[k] = *cmd == 'R';
is[k] = i;
vs[k] = v;
}

// here, 'rows' is the number of undeleted rows left
//       'cols' is the number of undeleted columns left
//       'sum' is the current sum
ll rows = n, cols = n, sum = 0;
for (int k = p - 1; k >= 0; k--) {
int i = is[k], v = vs[k];
if (ts[k]) { // this is a row update
if (deleted_rows.find(i) == deleted_rows.end()) {
deleted_rows.insert(i);
sum += cols * v;
rows--;
}
} else { // this is a column update
if (deleted_cols.find(i) == deleted_cols.end()) {
deleted_cols.insert(i);
sum += rows * v;
cols--;
}
}
}

// print the sum
printf("%lld\n", sum);
}

class Cell {
int x;
boolean isRow;
long value;
public Cell(String s) {
String[] ss = s.split(" ");
this.isRow = ss[0].charAt(0) == 'R';
this.x = Integer.parseInt(ss[1]);
this.value = Long.parseLong(ss[2]);
}
}
public static void main(String[] args) {
Solution sol = new Solution();

Scanner in = new Scanner(System.in);
String[] ss = in.nextLine().split(" ");
int N = Integer.parseInt(ss[0]);
int P = Integer.parseInt(ss[1]);

//Storage
HashMap<String, Cell> map = new HashMap<String, Cell>();
ArrayList<Cell> list = new ArrayList<Cell>();

while (P != 0) {//O(P)
//create Cell
String s = in.nextLine();
Cell cell = sol.new Cell(s);
//Check if cell exist in map.
//if exist in map, replace it with current cell, and remove old cell from list
String key = s.substring(0, s.lastIndexOf(" "));
if (!map.containsKey(key)) {
map.put(key, cell);
} else {
Cell oldCell = map.get(key);
map.put(key, cell);
list.remove(oldCell);
}
P--;
}

//Process final results
int sumCol = 0;
int sumRow = 0;
long sum = 0;
for (int i = 0; i < list.size(); i++) {//O(P)
Cell cell = list.get(i);
sum += cell.value * N;
if (cell.isRow) {
sum -= sumCol;
sumRow += cell.value;
} else {
sum -= sumRow;
sumCol += cell.value;
}
}

System.out.println(sum);
}