Filling a 2*n room with two different tiles - c++

I came across a problem where I have to fill a rectangle having 2 rows and n columns. There are two tiles one 1*2 tile and second a L shaped tile of larger sides having dimension 2 units and smaller sides having dimension 1 units.
I solved it through dynamic programming and am not pretty sure if it is working all right or not. If not what will be the correct bottom up code of this problem.
Below is the function snippet of my solution.
For the recurrence one column can be filled in one way putting the first tile vertically two adjacent columns can be filled in one way by putting the first type of tile horizontally one after the other. Three adjacent columns can be filled by aligning the two L-shaped in an inverted manner in 2 ways and four adjacent columns can be filled by two L-shape tile facing each other and the first type of tile lying horizontally in 2 ways.
int tileways(int n) //n=no.of columns of the rectangle.
{
int i;
int a[n+4];
a[0]=0;
a[1]=0;
a[2]=0;
a[3]=1;
for(i=4;i<n+4;i++)
{
a[i]=a[i-1]+a[i-2]+2*a[i-3]+2*a[i-4];
}
return a[n+3];
}

Using approach from my first comment.
l[3] configuration:
L[3] configurations:
#include <iostream>
using namespace std;
int tileways(int n) //n=no.of columns of the rectangle.
{
int l[20];//straight border
int L[20];//extra square
l[0] = 1;
l[1] = 1;
L[0] = 0;
L[1] = 1;
for (int i = 2; i <=n; i++) {
l[i] = l[i-1] + l[i-2] + 2*L[i-2];
//add | to the last straight, = to the 2nd last straight,
//two cases of L to extra
L[i] = l[i-1] + L[i-1];
//add L to the last straight, - to the extra
}
return l[n];
}
int main() {
for (int i = 1; i < 10; i++)
std::cout<<i<<" "<< tileways(i)<<std::endl;
return 0;
}
ideone result
1 1
2 2
3 5
4 11
5 24
6 53
7 117
8 258
9 569
For reference: OEIS sequence number of possible tilings of a 2 X n board, using dominos and L-shaped trominos.
1, 2, 5, 11, 24, 53, 117, 258

Related

create a matrix with condition in C++

I want to create a matrix B from a matrix A, in C++.
First column of A is distance D1, second column is distance D2. Matrix B copies the same columns (and rows) of A, except when in A it happens that D2-D1=delta exceeds a threshold. In this case, the row of A is break in two rows in B.
I wrote an algorithm, but the problem is that it gives segmentation fault. Someone can help, why it happens?
std::vector<float> newD1(10), newD2(10);
float box=5.;
int j=0;
for(auto i=0;i<D1.size();i++){
float delta=D2[i]-D1[i];
if (delta>box){ //break row i in two rows: j and j+1
//first half of row i goes in row j
newD1[j]=D1[i];
newD2[j]=(D1[i]+D2[i])/2.;
//second half of row i goes in j+1
D1[j+1]=(D1[i]+D2[i])/2.;
D2[j+1]=D2[i];
j=j+2; //we skip two row because we break up the original row in 2 rows
}
else{
newD1[j]=(D1[i]);
newD2[j]=D2[i];
j=j+1; //we skip one row because the original row is unchanged
}
}
Here I give you an example of matrix A and B; I also specify delta beside each line of the matrix.
Matrix A:
#D1 D2 delta
|0 5 | 5
A= |5 15 | 10 }--> exceed the threshold, delta>5. Must break in 2 rows in `B`
|15 17 | 2
B is created breaking the second line in two lines, because delta>5 :
#D1 D2 delta
|0 5 | 5
B= |5 10 | 5 }--> created from row #2 of `A`. `D2` is midpoint between`D1` and `D2` in row #2 in `A`
|10 15 | 5 }--> created from row #2 of `A`. `D1` is midpoint between`D1` and `D2` in row #2 in `A`
|15 17 | 2
EDIT:
What if I want to recursively break up the rows (e.g. suppose that at row #2 in A, delta>3*box, meaning that I need to break up that row in 3 rows in B). Any suggestions?
1.You can use push_back to avoid the size definition
2.You updated D1 and D2 instead of newD1 and newD2
#include <vector>
#include <iostream>
using namespace std;
int main()
{
std::vector<float> D1 = { 0,5,15 };
std::vector<float> D2 = { 5,15,17 };
std::vector<float> newD1, newD2;
float box = 5.;
for (auto i = 0; i < D1.size(); i++) {
float delta = D2[i] - D1[i];
if (delta > box) { //break row i in two rows: j and j+1
//first half of row i goes in row j
newD1.push_back(D1[i]);
newD2.push_back((D1[i] + D2[i]) / 2.);
//second half of row i goes in j+1
newD1.push_back ((D1[i] + D2[i]) / 2.);
newD2.push_back (D2[i]);
}
else {
newD1.push_back(D1[i]);
newD2.push_back(D2[i]);
}
}
}

Replace duplicate elements in an Array with minimum steps

I should make a program where in a given array of elements I should calculate the minimum amount of elements I should change in order to have no duplicates next to each other.
The windows are in every room and they are all at the same height, so when Mendo walks around the house and looks at them from the outside the windows look like they are stacked in a row. Mendo has three types of colors (white, gray and blue) and wants to color the windows so that there are no two windows that are the same color and are one after the other.
Write a program that will read from the standard input information about the number of windows and the price of coloring each of them with a certain color, and then print the minimum coloring cost of all windows on standard output.
The first line contains an integer N (2 <= N <= 20), which indicates the number of windows. In each of the following N rows are written 3 integers Ai, Bi, Ci (1 <= Ai, Bi, Ci <= 1000), where Ai, Bi, and Ci denote the coloring values of the i window in white , gray and blue, respectively.
Test case:
Input:
3 5 1 5
1 5 5
5 1 1
Output:
3
Also, I should keep in mind that the first element and the last one are considered neighbour-elements.
I started by sorting the array for some reason.
int main()
{
int N;
cin >> N;
int Ai, Bi, Ci;
int A[N * 3];
int A_space = 0;
for (int i = 0; i < N; i++) {
cin >> Ai >> Bi >> Ci;
A[A_space] = Ai;
A[A_space + 1] = Bi;
A[A_space + 2] = Ci;
A_space += 3;
}
for (int i = 0; i < N * 3; i++) {
for (int j = 0; j < N * 3; j++) {
if (A[j] > A[j + 1]) {
swap(A[j], A[j + 1]);
}
}
}
return 0;
}
This problem can be solved by dynamic programming. You will need an N x 3 matrix for this. You will need to calculate the minimum cost of painting the window on each of the 3 colors for each of the N windows. Note that for each color it is enough to take the minimum from the cost of painting N-1 windows on the other two colors because you cannot use the same color 2 times in a row.

How to count how many valid colourings in a graph?

I attempted this SPOJ problem.
Problem:
AMR10J - Mixing Chemicals
There are N bottles each having a different chemical. For each chemical i, you have determined C[i] which means that mixing chemicals i and C[i] causes an explosion. You have K distinct boxes. In how many ways can you divide the N chemicals into those boxes such that no two chemicals in the same box can cause an explosion together?
INPUT
The first line of input is the number of test cases T. T test cases follow each containing 2 lines.
The first line of each test case contains 2 integers N and K.
The second line of each test case contains N integers, the ith integer denoting the value C[i]. The chemicals are numbered from 0 to N-1.
OUTPUT
For each testcase, output the number of ways modulo 1,000,000,007.
CONSTRAINTS
T <= 50
2 <= N <= 100
2 <= K <= 1000
0 <= C[i] < N
For all i, i != C[i]
SAMPLE INPUT
3
3 3
1 2 0
4 3
1 2 0 0
3 2
1 2 0
SAMPLE OUTPUT
6
12
0
EXPLANATION
In the first test case, we cannot mix any 2 chemicals. Hence, each of the 3 boxes must contain 1 chemical, which leads to 6 ways in total.
In the third test case, we cannot put the 3 chemicals in the 2 boxes satisfying all the 3 conditions.
The summary of the problem, given a set of chemicals and a set of boxes, count how many possible ways to place these chemicals in boxes such that no chemicals will explode.
At first I used brute force method to solve the problem, I recursively place chemicals in boxes and count valid configurations, I got TLE at my first attempt.
Later I learned that the problem can be solved with graph colouring.
I can represent chemicals as vertexes and there'a an edge between chemicals if they cannot be placed each other.
And the set of boxes can be used as vertex colours, all I need to do was to count how many different valid colourings of the graph.
I applyed this concept to solve the problem unfortunately I got TLE again. I don't know how to improve my code, I need help.
code:
#include <bits/stdc++.h>
#define MAXN 100
using namespace std;
const int mod = (int) 1e9 + 7;
int n;
int k;
int ways;
void greedy_coloring(vector<int> adj[], int color[])
{
int u = 0;
for (; u < n; ++u)
if (color[u] == -1)//found first uncolored vertex
break;
if (u == n)//no uncolored vertexex means all vertexes are colored
{
ways = (ways + 1) % mod;
return;
}
bool available[k];
memset(available, true, sizeof(available));
for (int v : adj[u])
if (color[v] != -1)//if the adjacent vertex colored, make its color unavailable
available[color[v]] = false;
for (int c = 0; c < k; ++c)
if (available[c])
{
color[u] = c;
greedy_coloring(adj, color);
color[u] = -1;//don't forgot to reset the color
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
cin >> T;
while (T--)
{
cin >> n >> k;
vector<int> adj[n];
int c[n];
for (int i = 0; i < n; ++i)
{
cin >> c[i];
adj[i].push_back(c[i]);
adj[c[i]].push_back(i);
}
ways = 0;
int color[n];
memset(color, -1, sizeof(color));
greedy_coloring(adj, color);
cout << ways << "\n";
}
return 0;
}
Counting the number of colorings in a general graph is #P-hard, but this graph has some special structure, which I'll exploit in a minute after I enumerate some basic properties of counting colorings. The first observation is that, if the graph has a node with no neighbors, if we delete that node, the number of colorings decreases by a factor of k. The second observation is that, if a node has exactly one neighbor and we delete it, the number of colorings decreases by a factor of k-1. The third is that the number of colorings is equal to the product of the number of colorings for each connected component. The fourth is that we can delete all but one parallel edge.
Using these properties, it suffices to determine a formula for each connected component of the 2-core of this graph, which is a simple cycle of some length. Let P(n) and C(n) be the number of ways to color a path or cycle respectively with n nodes. We use the basic properties above to find
P(n) = k (k-1)^(n-1).
Finding a formula for C(n) I think requires the deletion contraction formula, which leads to a recurrence
C(3) = k (k-1) (k-2), i.e., three nodes of different colors;
C(n) = P(n) - C(n-1) = k (k-1)^(n-1) - C(n-1).
Multiply the above recurrence by (-1)^n.
(-1)^3 C(3) = -k (k-1) (k-2)
(-1)^n C(n) = (-1)^n k (k-1)^(n-1) - (-1)^n C(n-1)
= (-1)^n k (k-1)^(n-1) + (-1)^(n-1) C(n-1)
(-1)^n C(n) - (-1)^(n-1) C(n-1) = (-1)^n k (k-1)^(n-1)
Let D(n) = (-1)^n C(n).
D(3) = -k (k-1) (k-2)
D(n) - D(n-1) = (-1)^n k (k-1)^(n-1)
Now we can write D(n) as a telescoping sum:
D(n) = [sum_{i=4}^n (D(n) - D(n-1))] + D(3)
D(n) = [sum_{i=4}^n (-1)^n k (k-1)^(n-1)] - k (k-1) (k-2).
Break it down as two geometric sums which then cancel nicely.
D(n) = [sum_{i=4}^n (-1)^n ((k-1) + 1) (k-1)^(n-1)] - k (k-1) (k-2)
= sum_{i=4}^n (1-k)^n - sum_{i=4}^n (1-k)^(n-1) - k (k-1) (k-2)
= (1-k)^n - (1-k)^3 - k (k-1) (k-2)
= (1-k)^n - (1 - 3k + 3k^2 - k^3) - (2k - 3k^2 + k^3)
= (1-k)^n - (1-k)
C(n) = (-1)^n (1-k)^n - (-1)^n (1-k)
= (k-1)^n + (-1)^n (k-1).
Note that after removing all parallel edges, we can have at most n edges. This means that in any one connected component we can only see one cycle (and simple at that), which makes the combinatorics rather straightforward. (Cycles are only dependent on how many edges each node can spawn, which is capped at 1.)
Second example:
k = 3
<< 0 <-- 3
/ ^
/ ^
1 --> 2
Since cycles are self contained, any connection to one removes the possibility of another. In the example above, we cannot make a second cycle involving node 3 by adding more nodes, and the same issue would extend to any subsequent connected nodes.
It should be enough, therefore, to perform a search, separating out connected components and marking their node count and whether they contain a cycle. Given a connected component, where c of the nodes are part of a cycle and m nodes are not, we have the following formula (David Eisenstat helped me correct my combinatoric for the count of colourings of a cycle):
if the component has a cycle:
[(k - 1)^c + (-1)^c * (k - 1)] *
(k - 1)^(m)
otherwise:
k * (k - 1)^(m - 1)
As David Eisenstat noted, multiply all these results for the final tally.

Euclidean distance between each record with other records in an array

so i have an array [nm] and i need to code in c++ the Euclidean distance between each row and the other rows in the array and store it in a new distance-array [nn] which every cell's value is the distance between the intersected rows.
distance-array:
r0 r1 .....rn
r0 0
r1 0
. 0
. 0
rn 0
the Euclidean distance between tow rows or tow records is:
assume we have these tow records:
r0: 1 8 7
r1: 2 5 3
r2
.
.
rn
Euclidean distance between r0 and r1 = sqrt((1-2)^2+(8-5)^2+(7-3)^2)
to code this i used 4 loops(which i think is too much) but i couldn't do it right, can someone help me to code this without using 3-D array ??
this is my code:
int norarr1[row][column] = { 1,1,1,2,2,2,3,3,3 };
int i = 0; int j = 0; int k = 0; int l = 0;
for (i = 0; i < column; i++){
for(j = 0; j < column; j++){
sumd = 0;
for (k = 0; k < row; k++) {
for (l = 0; l < row; l++) {
dist = sqrt((norarr1[i][k] - norarr1[j][l]) ^ 2);
sumd = sumd + dist;
cout << "sumd =" << sumd << " ";
}
cout << endl;
}
disarr[j][i] = sumd;
disarr[i][j] = sumd;
cout << disarr[i][j];
}
cout << endl;
}
There are several problems with your code. For now, let's ignore the for loops. We'll get to that later.
The first thing is that ^ is the bitwise exclusive or (XOR) operator. It does not do exponentiation like in some other languages. Instead, you need to use std::pow().
Second, you are summing square roots, which is not the correct way to calculate Euclidean distance. Instead, you need to calculate a sum and then take the square root.
Now let's think about the for loops. Assume that you already know which two rows you want to calculate the distance between. Call these r1 and r2. Now you just need to pair one coordinate from r1 with one coordinate from r2. Note that these coordinates will always be in the same column. This means that you only need one loop to calculate the squares of the differences of each pair of coordinates. Then you sum these squares. Finally after this single loop you take the square root.
With that out of the way, we need to iterate over the rows to choose each r1 and r2. Okay, this will take two loops since we want each of these to take on the value of each row.
In total, we will need three for loops. You can make this easier to understand by designing your code well. For example, you can create a class or struct that holds each row. If you know that every row is only three dimensions, then create a point or vector3 class. Now you can write a function which calculates the distance between two points. Finally, store the list of points as a 1D array. In fact, breaking up the data and calculation in this way makes the previous discussion about calculating the distance even easier to understand.

Diagonally Sorting a Two Dimensional Array in C++ [duplicate]

I'm building a heatmap-like rectangular array interface and I want the 'hot' location to be at the top left of the array, and the 'cold' location to be at the bottom right. Therefore, I need an array to be filled diagonally like this:
0 1 2 3
|----|----|----|----|
0 | 0 | 2 | 5 | 8 |
|----|----|----|----|
1 | 1 | 4 | 7 | 10 |
|----|----|----|----|
2 | 3 | 6 | 9 | 11 |
|----|----|----|----|
So actually, I need a function f(x,y) such that
f(0,0) = 0
f(2,1) = 7
f(1,2) = 6
f(3,2) = 11
(or, of course, a similar function f(n) where f(7) = 10, f(9) = 6, etc.).
Finally, yes, I know this question is similar to the ones asked here, here and here, but the solutions described there only traverse and don't fill a matrix.
Interesting problem if you are limited to go through the array row by row.
I divided the rectangle in three regions. The top left triangle, the bottom right triangle and the rhomboid in the middle.
For the top left triangle the values in the first column (x=0) can be calculated using the common arithmetic series 1 + 2 + 3 + .. + n = n*(n+1)/2. Fields in the that triangle with the same x+y value are in the same diagonal and there value is that sum from the first colum + x.
The same approach works for the bottom right triangle. But instead of x and y, w-x and h-y is used, where w is the width and h the height of rectangle. That value have to be subtracted from the highest value w*h-1 in the array.
There are two cases for the rhomboid in the middle. If the width of rectangle is greater than (or equal to) the height, then the bottom left field of the rectangle is the field with the lowest value in the rhomboid and can be calculated that sum from before for h-1. From there on you can imagine that the rhomboid is a rectangle with a x-value of x+y and a y-value of y from the original rectangle. So calculations of the remaining values in that new rectangle are easy.
In the other case when the height is greater than the width, then the field at x=w-1 and y=0 can be calculated using that arithmetic sum and the rhomboid can be imagined as a rectangle with x-value x and y-value y-(w-x-1).
The code can be optimised by precalculating values for example. I think there also is one formula for all that cases. Maybe i think about it later.
inline static int diagonalvalue(int x, int y, int w, int h) {
if (h > x+y+1 && w > x+y+1) {
// top/left triangle
return ((x+y)*(x+y+1)/2) + x;
} else if (y+x >= h && y+x >= w) {
// bottom/right triangle
return w*h - (((w-x-1)+(h-y-1))*((w-x-1)+(h-y-1)+1)/2) - (w-x-1) - 1;
}
// rhomboid in the middle
if (w >= h) {
return (h*(h+1)/2) + ((x+y+1)-h)*h - y - 1;
}
return (w*(w+1)/2) + ((x+y)-w)*w + x;
}
for (y=0; y<h; y++) {
for (x=0; x<w; x++) {
array[x][y] = diagonalvalue(x,y,w,h);
}
}
Of course if there is not such a limitation, something like that should be way faster:
n = w*h;
x = 0;
y = 0;
for (i=0; i<n; i++) {
array[x][y] = i;
if (y <= 0 || x+1 >= w) {
y = x+y+1;
if (y >= h) {
x = (y-h)+1;
y -= x;
} else {
x = 0;
}
} else {
x++;
y--;
}
}
What about this (having an NxN matrix):
count = 1;
for( int k = 0; k < 2*N-1; ++k ) {
int max_i = std::min(k,N-1);
int min_i = std::max(0,k-N+1);
for( int i = max_i, j = min_i; i >= min_i; --i, ++j ) {
M.at(i).at(j) = count++;
}
}
Follow the steps in the 3rd example -- this gives the indexes (in order to print out the slices) -- and just set the value with an incrementing counter:
int x[3][3];
int n = 3;
int pos = 1;
for (int slice = 0; slice < 2 * n - 1; ++slice) {
int z = slice < n ? 0 : slice - n + 1;
for (int j = z; j <= slice - z; ++j)
x[j][slice - j] = pos++;
}
At a M*N matrix, the values, when traversing like in your stated example, seem to increase by n, except for border cases, so
f(0,0)=0
f(1,0)=f(0,0)+2
f(2,0)=f(1,0)+3
...and so on up to f(N,0). Then
f(0,1)=1
f(0,2)=3
and then
f(m,n)=f(m-1,n)+N, where m,n are index variables
and
f(M,N)=f(M-1,N)+2, where M,N are the last indexes of the matrix
This is not conclusive, but it should give you something to work with. Note, that you only need the value of the preceding element in each row and a few starting values to begin.
If you want a simple function, you could use a recursive definition.
H = height
def get_point(x,y)
if x == 0
if y == 0
return 0
else
return get_point(y-1,0)+1
end
else
return get_point(x-1,y) + H
end
end
This takes advantage of the fact that any value is H+the value of the item to its left. If the item is already at the leftmost column, then you find the cell that is to its far upper right diagonal, and move left from there, and add 1.
This is a good chance to use dynamic programming, and "cache" or memoize the functions you've already accomplished.
If you want something "strictly" done by f(n), you could use the relationship:
n = ( n % W , n / H ) [integer division, with no remainder/decimal]
And work your function from there.
Alternatively, if you want a purely array-populating-by-rows method, with no recursion, you could follow these rules:
If you are on the first cell of the row, "remember" the item in the cell (R-1) (where R is your current row) of the first row, and add 1 to it.
Otherwise, simply add H to the cell you last computed (ie, the cell to your left).
Psuedo-Code: (Assuming array is indexed by arr[row,column])
arr[0,0] = 0
for R from 0 to H
if R > 0
arr[R,0] = arr[0,R-1] + 1
end
for C from 1 to W
arr[R,C] = arr[R,C-1]
end
end