Here is the problem statement:
*Chef is working with lines on a 2-D plane. He knows that every line on a plane can be clearly defined by three coefficients A, B and C: any point (x, y) lies on the line if and only if A * x + B * y + C = 0. Let's call a set of lines to be perfect if there does not exist a point that belongs to two or more distinct lines of the set. He has a set of lines on a plane and he wants to find out the size of the largest perfect subset of this set.
Input
The first line of input contains one integers T denoting the number of test cases. Each test case consists of one integer N denoting number of lines. Next N lines contain 3 space-separated integers each denoting coefficients A, B and C respectively.
Output
For each test case output the cardinality of the largest perfect subset in a single line. Constraints
Input:
1 5
1 1 0
1 2 3
3 4 5
30 40 0
30 40 50
Output: 2 Explanation
Lines 3*x + 4*y + 5 = 0 and 30*x + 40*y + 0 = 0 form a biggest perfect subset.*
So if the ratios of As and Bs are the same, then the lines would be parallel which fulfills the problem statement. For example: if A[1] / B[1] == A[2] / B[2] then these line one and line two are parallel. But when the two lines in question are the same lines, which means there are an infinite number of common points, this equation holds, which is not what the problem wants. So we need to use C to determine whether the lines are the same or not (i.e. A[1]/A[2] == B[1]/B[2] == C[1]/C[2]). But the code I wrote with these ideas are so inefficient. Can you all suggest a more time-efficient solution?
You can write a linear algorithm for this.
The idea is to have a map, where the key is a direction and the value is a set.
For each direction, the set contains only different lines which have the given direction. Then the answer is the size of the larger set.
The direction of a line Ax + By + C = 0 is A/B. The problem is that if B=0 it won't quite work as a key.
You can have a special set for the case B=0, which you keep separate and don't insert into the map.
The values that you insert into the set for a given line Ax + By + C = 0, should be C/B.
In the special case, when B = 0, you should use C/A.
Related
How to find the numbers of ways to fill a grid (3*n)array, with three colors A, B and C.
Under the following constraints:
1) All the n cells of the same row can't have the same color.
2) All the 3 cells of the same column can't have the same color.
Sample input : if n=2, then output or number of ways = 174.
Please explain the approach for this.
This answer given by sam29 on codefores.
We can solve this question using Inclusion-Exclusion principle. So, let's first consider only the first column of the matrix. We can easily deduce that there are 24 different ways to fill that column keeping in mind that we can't have the same letter in the complete column. Now, we can directly say that the total ways to fill the complete matrix will be 24^N (Name this value as X1). In this answer, we have made sure that all the column contains distinct alphabets. But we need to consider the cases a row contains the same letter. So, now we will use inclusion-exclusion principle.
Find the number of cases with one row same. Fix 'A' in the first row. Now, take only the first column and you can deduce that there are 8 distinct ways to fill the 2nd and the 3rd row of the first column keeping in mind we can't have the same letter in the complete column. So, now we can find the total number of ways to fill all the N rows as 8^N. Now, we can do the same thing with 'B' and 'C' in the first row and similarly, we can repeat the process for the 2nd and the 3rd row. So, the total number of ways will be 9*8^N (Name this value as X2).
Find the number of cases with two rows same (Name this value as X3). This is the trickiest part of the question. I'll explain this at last.
Find the number of cases with all the three rows same but we can't have the same letter in a single column. This is pretty easy and is equivalent to the number of ways to fill a single column and 3 rows. So, the answer is 24 for this scenario (Name this value as X4).
Now, the final answer will be X1-X2+X3-X4.
Now, coming back to the answer for 2nd scenario. So, we will try to find the answer for the case when the first row and second row is same and we can repeat that process for the 2nd row and 3rd row AND 1st row and 3rd row. Basically, we can multiply the answer we will calculate now with 3. Okay, now take only the first column. Now, you can see that there will be 2 scenarios, one will be when the first and second row contains the same letter and in that case, we have to place a different letter in the 3rd row because else we will violate our condition of the distinct column. So, the total number of ways in the first scenario will be 3*2^N (I have skipped some part but I have provided the exact reason and a little further thinking and you will get the solution). Now, for the next scene when the first and second row contains different letters. In that case, you can place any letter in the 3rd row. Again try to think a little more and you will get the answer as 6*3^N. So, the total answer will be 3*2^N + 6*3^N. And as I said before we need to multiply it by 3 (Number of ways to choose 2 rows from 3 rows). So, X3 will be 3*(3*2^N + 6*3^N).
The complexity is pretty direct, you can do precomputation or apply exponent function every time.
Thanks.
This is combinatorial question, for sure it is better to post questions like this on math.stackexchange.com.
A row can be in two different configurations: having two colors (ABA) and having three colors (ABC). If we have last row of some configuration, lets check possibilities for next row.
A | B B B C C
B | A A C A A
A | B C B B C
A | B B B C
B | A C C A
C | B A B B
Set:
A_n : number of dimension n matrices where last row is of ABA configuration,
C_n : number of dimension n matrices where last row is of ABC configuration,
X_n : number of dimension n matrices = A_n + C_n.
From upper list of possibile next row it holds:
A_n = 3 * A_(n-1) + 2 * C_(n-1) = 2 * X_(n-1) + A_(n-1)
C_n = 2 * A_(n-1) + 2 * C_(n-1) = 2 * X_(n-1)
=>
X_n = 4 * X_(n-1) + A_(n-1)
Result to question is X_n, for which calculation A_n is needed, and initial values are A_1=6, X_1=12.
Update:
Search in OEIS for values 2, 9, 41, 187 (upper sequence if colors are not important, real number divided by 6), produces sequence A020698. Sequence mentions similar problem, and suggests that upper recursion can be stated in simpler manner:
X_n = 4 * X_(n-1) + A_(n-1)
= 4 * X_(n-1) + A_(n-1) + X_(n-1) - X_(n-1)
= 5 * X_(n-1) + 2 * X_(n-2) + A_(n-2) - 4 * X_(n-2) - A_(n-2)
= 5 * X_(n-1) - 2 * X_(n-2)
First here is the question,
Say that an integer can be represented as a perfect sphere, in which the value of the sphere is equal to the integer it contains. The spheres are organized into a tetrahedral pyramid in which N = the length of the side, N being between 1 and 15. Pick (a possibly empty) subset of sphere's such that their sum of values is maximized. Note that the sphere can hold a negative value so it is not necessarily desirable to pick up every sphere. We do not want to disorganize the pyramid so we cannot take any one sphere without first taking the ones above it.
Input Format:
Line 1: integer N
Line 2: N(N+1)/2+1
Output Format:
Line 1: One integer, the maximum sum of values achievable
Sample Input:
3
5
-2 -7
-3
1 0 8
0 3
2
Sample Output:
8
Here is a sample solution given to my understanding so far:
The best solution is shown as bold in the diagram bellow. It is not smart to take 1 because that would require taking -2, decreasing the total. There for 8, 3, and 2 should be taken because they outweigh -3 and -7.
My question is,
How do I store the input so that I can retain the proper order? Or do i even need to? I am trying to use a queue but my program gets very lengthly because I have to find the sum for each possible path and then compare each sum to find the max. I am also having a lot of difficulty breaking the data up into the right pattern so I don't recount a number or take one out of sequence. Is there a more efficient way to do this? Can Dijkstra's algorithm be of any use in this case? If so, then how? Any help is greatly appreciated!!
I would use a 3-dimensional array. To use your example:
A[0][0][0] = 5
A[1][0][0] = -2
A[1][1][0] = -3
A[1][0][1] = -7
A[2][0][0] = 1
A[2][1][0] = 0
A[2][2][0] = 2
A[2][0][0] = 0
A[2][1][0] = 3
A[2][0][0] = 8
The "above" relationship is simply a matter of index arithmetic: [ia, ja, ka] is above [ia+1, ja, ka], [ia+1, ja+1, ka] and [ia+1, ja, ka+1].
I have a problem, I want to generate a table of 4 columns and 1 line, and with integers in the range 0 to 9, without repeating and are random each time it is run.
arrives to this, but I have a problem I always generates a 0 in the first element. And i dont know how to put a limit of 0-9
anyone who can help me?
Code of Function:
function [ n ] = generar( )
n = [-1 -1 -1 -1];
for i = 1:4
r=abs(i);
dig=floor((r-floor(r))*randn);
while find (n == dig)
r=r+1;
dig=dig+floor(r-randn);
end
n(i)=dig;
end
end
And the results:
generar()
ans =
0 3 9 6
generar()
ans =
0 2 4 8
I dont know if this post is a duplicate, but i need help with my specific problem.
So assuming you want matlab, because the code you supplied is matlab, you can simply do this:
randperm(10, 4) - 1
This will give you 4 unique random numbers from 0-9.
Another way of getting there is randsample(n, k) where n is an integer, then a random sample of size k will be drawn from the population 1:n (as a column vector). So for your case, you would get the result by:
randsample(10, 4)' - 1
It draws 4 random numbers from the population without replacement and all with same weights. This might be slower than randperm(10, 4) - 1 as its real strength comes with the ability to pass over population vectors for more sophisticated examples.
Alternatively one can call it with randsample(pop, k) where pop is the population-vector of which you want to draw a random sample of size k. So for your case, one would do:
randsample(0:9, 4)
The result will have the same singleton dimension as the population-vector, which in this case is a row vector.
Just to offer another solution and get you in touch with randsample().
Consider a [4x8] matrix "A" and [1x8] matrix "B". I need to check if there exists a value "X" such that
[A]^T * [X] = [B]^T exists for any x >= 0 { X is a [4X1] matrix, T = transpose }
Now here is the trick/tedious part. The matrix A always has 1 as its diagonal. A11,A22,A33,A44 = 1 This matrix can be considered as two halves with first half being the first 4 columns and the second half being the second 4 columns like something below :
1 -1 -1 -1 1 0 0 1
A = -1 1 -1 0 0 1 0 0
-1 -1 1 0 1 0 0 0
-1 -1 -1 1 1 1 0 0
Each row in the first half can have either two or three -1's and if it has two -1's then that corresponding row in the second half should have one "1" or if any row has three -1's the second half of the matrix should have two 1's. The overall objective is to have the sum of each row to be 0.
Now B is a [1x8] matrix which can also be considered as two halves as follows:
B = -1 -1 0 0 0 0 1 1
Here there can be either one, two, three or four -1's in the first half and there should be equal number of 1's in the second half. It should be done in combinations For example, if there are two -1's in the first half, they can be placed in 4 choose 2 = 6 ways and for each of them there will be 6 ways to place the 1's in the second half which has a total of 6*6 = 36 ways. i.e. 36 different values for B's if there are two -1's in the first half. The placement of 1's in the matrix A should also be the same way. The way I could think of doing this is to consider a valarray or something of that sort and make the matrices A and B but I don't know what to do.
Now for every A, I've to test it with every combinations of B to see if there exists
[A]^T * [X] = [B]^T
I'm trying to prove a result that I got I need to know if such an X would exist or not. I'm very confused on implementing this. Any suggestions are welcome. This would come under linear programming concept in math. I want it either in C++ or in Matlab. Any other languages are also acceptable but I'm familiar with only these two. Thanks in advance.
Update:
Here is my answer for this problem :
clear;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%# Generating all possible values of vector B
%# permutations using dec2bin (start from 17 since it's the first solution)
vectorB = str2double(num2cell(dec2bin(17:255)));
%# changing the sign in the first half, then check that the total is zero
vectorB(:,1:4) = - vectorB(:,1:4);
vectorB = vectorB(sum(vectorB,2)==0,:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%# generate all possible variation of first/second halves
z = -[0 1 1; 1 0 1; 1 1 0; 1 1 1]; n = -sum(z,2);
h1 = {
[ ones(4,1) z(:,1:3)] ;
[z(:,1:1) ones(4,1) z(:,2:3)] ;
[z(:,1:2) ones(4,1) z(:,3:3)] ;
[z(:,1:3) ones(4,1) ] ;
};
h2 = arrayfun(#(i) unique(perms([zeros(1,4-i) ones(1,i)]),'rows'), (1:2)', ...
'UniformOutput',false);
%'# generate all possible variations of complete rows
rows = cell(4,1);
for r=1:4
rows{r} = cell2mat( arrayfun( ...
#(i) [ repmat(h1{r}(i,:),size(h2{n(i)-1},1),1) h2{n(i)-1} ], ...
(1:size(h1{r},1))', 'UniformOutput',false) );
end
%'# generate all possible matrices (pick one row from each to form the matrix)
sz = cellfun(#(M)1:size(M,1), rows, 'UniformOutput',false);
[X1 X2 X3 X4] = ndgrid(sz{:});
matrices = cat(3, ...
rows{1}(X1(:),:), ...
rows{2}(X2(:),:), ...
rows{3}(X3(:),:), ...
rows{4}(X4(:),:) );
matrices = permute(matrices, [3 2 1]); %# 4-by-8-by-104976
A = matrices;
clear matrices X1 X2 X3 X4 rows h1 h2 sz z n r
options = optimset('LargeScale','off','Display','off');
for i = 1:size(A,3),
for j = 1:size(vectorB,1),
X = linprog([],[],[],A(:,:,i)',vectorB(j,:)');
if(size(X,1)>0) %# To check that it's not an empty matrix
if((size(find(X < 0),1)== 0)) %# to check the condition X>=0
if (A(:,:,i)'* X == (vectorB(j,:)'))
X
end
end
end
end
end
I got it with the help of stackoverflow folks. The only problem is the linprog function throws a lot of exceptions in every iteration along with the answers produced. The exception is:
(1)Exiting due to infeasibility: an all-zero row in the constraint matrix does not have a zero in corresponding right-hand-side entry.
(2) Exiting: One or more of the residuals, duality gap, or total relative error has stalled: the primal appears to be infeasible (and the dual unbounded).(The dual residual < TolFun=1.00e-008.
What does this mean. How can I overcome this?
It is not clear from your question if you are familiar with system linear equations and their solution, or it is what you are trying to "invent". See also here for Matlab-specific explanation.
If you are familiar with that, you should be more clear in your question about what makes your problem different.
Well, after solving this problem by naive STL set,I was reading the forum entries,there I find this entry :
#include <iostream>
#include <cmath>
#define MAX 100
using namespace std;
int main(){
int res=(MAX-1)*(MAX-1);
for(int i=2;i<MAX;i++)
for(int j=i*i;j<=MAX;j=j*i)
res = res-int(MAX*(log(i)/log(j)))+1;
cout<<res<<endl;
return 0;
}
The author's explanation :
Maximum will be 99*99. I subtracted occurrences of those numbers which are powers of some lower numbers (2-100): -
For example: -
4^2,4^3,4^4 (i.e. 3 should be subtracted) as they will be duplicates from lower number powers as in 2^4,2^6,2^8
This program is giving correct answer check here but I am unable to get the implemented logic,to be precise I am not getting how the duplicates are determined. Could somebody help ?
I may be missing something, but it seems to me this program gives the wrong answer. It's off by one. If I set MAX to 10, it's off by two.
I have read that some players like to produce approximate answers and then dictionary-attack the Project Euler servers to brute-force the problem. Other players consider that rather against the spirit of the thing.
Anyway—an algorithm like this (starting with N*M and eliminating duplicates) is the right way to tackle the problem, but as written this code doesn't make much sense to me. Note that in any case int(MAX*(log(i)/log(j))) is very sensitive to rounding error; but even if you eliminate that source of error by using integer arithmetic, the program still gives the wrong answer.
EDIT: How can we (correctly) count the duplicates?
First you must understand that two numbers are only the same if they have the same prime factorization. So there are only going to be duplicates a1b1 = a2b2 when a1 and a2 are distinct integer powers of the same integer, which I'll call x. For example,
97 = 314; this is possible because 9 and 3 are both powers of 3.
86 = 49; this is possible because 8 and 4 are both powers of 2.
So we have established that for all duplicates, a1 = xe1 and a2 = xe2 for some integers x, e1, and e1.
Then with a little algebra,
a1b1 = a2b2
xe1b1 = xe2b2
e1b1 = e2b2
Going back to the earlier examples,
97 = 314 because 2×7 = 1×14.
86 = 49 because 3×6 = 2×9.
So to find all duplicates for any given x, you only need to find duplicates for the simpler expression eb where 2 ≤ xe ≤ 100 and 2 ≤ b ≤ 100.
Here is a picture of that simpler problem, for x=3 and b ranging only from 2 to 10. I've marked two places where there are duplicates.
e=1 a=3 *********
e=2 a=9 * * * * * * * * *
e=3 a=27 * * * * * * * * *
e=4 a=81 * * * * * * * * *
| |
1*8 = 2*4 = 4*2 3*8 = 4*6
3^8 = 9^4 = 81^2 27^8 = 81^6
And here are the duplicates:
e=1 a=3 *********
e=2 a=9 x x x x * * * * *
e=3 a=27 x x x * x * * * *
e=4 a=81 x x x x x * * * *
The C++ program you found is trying to count them by visiting each pair of overlapping rows i and j, and calculating how much of row i overlaps row j. But again, unless I'm missing something, the program seems hopelessly imprecise. And it misses some pairs of rows entirely (you never have i=9 and j=27, or i=27 and j=81).
first, it sets res to 99*99 at line 6, because MAX was defined as 100. Then it enters a loop, with the condition that i is smaller than MAX. then it enters this pseudocode loop
int i;
int j;
int x=2;
for( j = i2; j <= MAX , j = ix)
{
res = res- (MAX* ( jlog(i) )+1;
x++;
}
sorry 'bout the not using <pre><code> above; but if I did I could not use <sup>
Please note log(a)/log(x) is the same as xlog(a)
comments on question because <sup> does not work there:
2log(2) = 1 because 21 = 2
2log(4) = 2 because 22 = 2
log(x) == 10log(x)
log(10) = 1
glog(x) = y => gy = x
Well, the question involves ways to combine two numbers chosen from a range. There are 99 possible numbers, so the number of combinations is 99 * 99, with possible duplicates. His basic algorithm here is to figure out how many duplicates are present, and subtract that value from the maximum.
As for counting duplicates, it might help intuitively to think of the numbers in terms of their prime factors. Raising a number to an integer power means multiplying it by itself; so, represented as a list of primes, this is equivalent to simply concatenating the lists. For instance, 6 is {2, 3}, so 6^3 would be {2, 2, 2, 3, 3, 3}. Note that if you count how many times each prime appears in the list, x^n will always have the same proportions as x, for instance 6^n will have an equal quantity of 2's and 3's. So, any two numbers in the range with the same proportion between primes must both be powers of some number.
So, in the full list, each distinct proportion of prime factors will appear repeatedly as x^2, x^3, x^4..., (x^3)^2, (x^3)^4..., (x^4)^2..., etc., where x is the smallest number with that proportion; more precisely, (x^m)^n where (x^m) <= 100 and 2 <= n <= 100. Since (x^m)^n is equal to x^(mn), counting duplicates amounts to counting the ways that x^(mn) can also be <= 100.
There are (at least) two ways to approach this problem. One is to start your count of distinct values at 0, and add one for each calculated value that hasn't been seen before. The other way is to calculate the maximum number of values, and then subtract one for each duplicate.
The poster is attempting the second methed. a can range from 2 to 100 for 99 values, as can b, so there are 99 * 99 produced values. The poster then attempts to subtract the duplicate values to get the correct answer.
Edit: However, the poster has written an incorrect algorithm.
For instance, setting MAX = 8 or 9. For 8 it should give 44 but it gives 45. For 9 it should give 54 but gives 56. Either they lucked out and happened across an algorithm that gives the correct answer for some inputs, or they reverse-engineered an algorithm that worked when MAX = 100 but not for all other values.