Solutions to fair distribution programming problems [closed] - algorithm

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have run into a wall since I attended a coding contest. I think this problem falls into the category of fair distribution, but I am not sure.
I am attaching the problem here.
I have come out with an empirical formula so which I tested successfully for 3 iterations attached here.
I am unable to come up with a working code that can solve this programming problem. Any help is appreciated.

Throughout the solution, I use A for hotel and B for house
Let us define 3 types of arrangements:
Arrangement ending with A||B, that is hotel on left and house on right.
Arrangement ending with B||A, that is house on left and hotel on right.
Arrangement ending with B||B, that is house on both sides.
Let us denote the respective arrays:
Array one[i] denotes number of arrangements of type 1 having street length i
Array two[i] denotes number of arrangements of type 2 having street length i
Array three[i] denotes number of arrangements of type 3 having street length i
Any arrangement of type 1, can be extended when the street length increases by 1 as follows:
B||A
A||B [A Type 2 arrangement]
B||B
A||B [A Type 3 arrangement]
Any arrangement of type 2, can be extended when the street length increases by 1 as follows:
A||B
B||A [A Type 1 arrangement]
B||B
B||A [A Type 3 arrangement]
Any arrangement of type 3, can be extended when the street length increases by 1 as follows:
A||B
B||B [A Type 1 arrangement]
B||A
B||B [A Type 2 arrangement]
B||B
B||B [A Type 3 arrangement]
When street length is 1:
one[1] = two[1] = three[1] = 1 (As explained in the sample test case)
When street length is i:
one[i] = two[i-1] + three[i-1]
two[i] = one[i-1] + three[i-1]
three[i] = one[i-1] + two[i-1] + three[i-1]
For a street length of size n, your answer is (one[n] + two[n] + three[n]) % 10^9+7
As n can be very huge, you need to come up with a general formula for the value of (one[n] + two[n] + three[n]) % 10^9+7
For n=1: result = 3
For n=2: result = 7
For n=3: result = 17
For n=4: result = 41
Verify the above results yourself!!!
Edit: You can use Matrix exponentiation to find out the result for different values of n in O(logn) time. Have a look here for more details!!!
You can use a matrix to represent the recurrence relation.
(one[n+1]) = ( 0 1 1 ) (one[n])
(two[n+1]) ( 1 0 1 ) (two[n])
(three[n+1]) ( 1 1 1 ) (three[n])
With this representation, it's feasible to compute values for large n, by matrix exponentation (modulo 10^9+7), using exponentation by squaring. That'll give you the result in O(log n) time.
(one[n]) = ( 0 1 1 )^(n-1) (1)
(two[n]) ( 1 0 1 ) (1)
(three[n]) ( 1 1 1 ) (1)
Happy Coding....

Related

How to derive the big O of this algorithm? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Improve this question
This is the algorithm:
for i ← 1 to n by 1 do
for j ← 1 to i by 1 do
for k ← 1 to j by 1 do
x = x + 1
end
end
end
The number of times the inner loop iterate, depends on the outer loops... so how can the time complexity be derived?
This algorithm increases π‘₯ with the 𝑛th tetrahedral number. This is because the loops can be seen as sums over a range:
The outer loop: βˆ‘π‘–π‘›= 1
The middle loop: βˆ‘π‘—π‘–= 1
The inner loop: βˆ‘π‘˜π‘—= 1
The inner statement: runs in constant time, so that counts as 1 operation.
This means the inner statement runs this many times:
βˆ‘π‘–π‘›= 1 ( βˆ‘π‘—π‘–= 1 ( βˆ‘π‘˜π‘—= 1
1 ) )
The inner sum really is 𝑗, so we can write:
βˆ‘π‘–π‘›= 1 ( βˆ‘π‘—π‘–= 1
𝑗 )
We recognise this expression as the tetrahedral number (see formula at above link to Wikipedia)
This double sum is 𝑛(𝑛 + 1)(𝑛 + 2)/6 = ΞΈ(𝑛³)
Another way to see this, is that the loops lead to combinations for 𝑖, 𝑗, and π‘˜ where they appear in non-decreasing order. So the number of times x = x + 1 is executed, corresponds to the number of ways we can select a multiset of three values from the range 1..𝑛, allowing duplicates. This number is "𝑛 multichoose 3", which leads to the same formula.

Count integers up to n that contain the digits 2018 in order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Given an integer n between 0 and 10,0000,0000, count the number of integers smaller than n which contain the digits [2,0,1,8] in order.
So e.g. the number 9,230,414,587 should be counted, because removing the digits [9,3,4,4,5,7] leaves us with [2,0,1,8].
Example input and output:
n = 2018 -> count = 1
n = 20182018 -> count = 92237
My general thought is that: the maximum length of n is 10 and the worst situation is that we have to insert 6 digits into [2,0,1,8] and remove the duplicates and the numbers greater than n.
I don't see any own attempts to solve, so I'll give only clue:
You have 9-digits number (small numbers might be represented as 000002018) containing digit sequence 2,0,1,8.
Name them 'good' ones.
Let denote digit places from 1 to 9 right to left:
number 532705183
digits 5 3 2 7 0 5 1 8 3
index 9 8 7 6 5 4 3 2 1
The most left '2' digit can occupy places from 4 to 9. How many good numbers contain the first 2 at k-th place? Let make function F2(l, k) for quantity of good numbers where 2 refers to digit 2, l is number length, k is place for the most left digit.
. . . . 2 . . . .
^
|
left part k right part should contain 0 1 8 sequence
without 2's
F2(9, k) = 9^(9-k) * Sum(F0(k-1, j) for j=1..k-1)
Overall quantity of good numbers is sum of F2(9, k) for all possible k.
GoodCount = Sum(F2(9, k) for k=4..9)
Explanation:
There are 9-k places at the left. We can put any digit but 2 there, so there are 9^(9-k) possible left parts.
Now we can place 0 at the right part and count possible variants for 018 subsequences. F0(...) will of course depend on F1(...) and F1 will depend on F8(...) for shorter numbers.
So fill tables for values for F8, F0, F1 step-by-step and finally calculate result for digit 2.
Hand-made example for 4-digit numbers containing subsequence 1 8 and k = position of the first '1':
k=2: there are 81 numbers of kind xx18
k=3: there are numbers of kind x1x8 and x18x
there are 9 subnumbers like x8, 10 subnumbers 8x, so (10+9)*9=171
k=4: there are numbers of kind
1xx8 (9*9=81 such numbers),
1x8x (9*10=90 numbers),
18xx (100 numbers),
so 81+90+100=271
Overall: 81+171+271=523
This is actually a relatively small problem set. If the numbers were much bigger, I'd opt to use optimised techniques to just generate all numbers that meet your criteria (those containing the digits in that order) rather than generating all possible numbers and checking each to ensure it meets the criteria.
However, the brute force method does your 20182018 variant in about ten seconds and the full 1,000,000,000 range in a little under eight minutes.
So, unless you need it faster than that, you may find the brute-force method more than adequate:
import re
num = 1000000000 # or 20182018 or something else.
lookfor = re.compile("2.*0.*1.*8")
count = 0
for i in range(num + 1):
if lookfor.search(str(i)) is not None:
count += 1
#print(count, i) # For checking.
print(count)

Not getting the approach in a minimization algorithm [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Recently, I was trying to solve this dynamic programing problem, but somehow not getting the approach to solve it.
The editorial to the problem seems very confusing too and i would understand how to think properly to approach this problem.
Thanks.
The problem
F. Yet Another Minimization Problem: Time limit per test: 2 seconds |
Memory limit per test: 256 megabytes |
Input: standard input |
Output: standard output
You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.
Input
The first line contains two integers n and k (2 ≀ n ≀ 105, 2 ≀ k ≀ min (n, 20)) - the length of the array and the number of segments you need to split the array into.
The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n) - the elements of the array.
Output
Print single integer: the minimum possible total cost of resulting subsegments.
Example 1
input
7 3
1 1 3 3 3 2 1
output
1
Example 2
input
10 2
1 2 1 2 1 2 1 2 1 2
output
8
Example 3
input
13 3
1 2 2 2 1 2 1 1 1 2 2 1 1
output
9
Note:
In the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.
In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.
In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1.
Understanding the problem
You just need to count the number of pairs in the serie of numbers (line 2) divised by k (line 1, second number)
From the example 2:
10 2
1 2 1 2 1 2 1 2 1 2
[numbers length] [divider]
[serie of numbers]
Take a look about the serie of numbers:
1 2 1 2 1 2 1 2 1 2
You need to divide by 2 the serie as an minimum total cost by pairs
[1,2,1,2,1] [2,1,2,1,2]
Then count the numbers of pairs for each number:
[1,2,1,2,1]
1 => [2,1,2,1] = 2 pairs
2 => [1,2,1] = 1 pair
1 => [2,1] = 1 pair
2 => [1] = 0
1 => [] = 0
Sum = 4 pairs
[2,1,2,1,2]
2 => [1,2,1,2] = 2 pairs
1 => [2,1,2] = 1 pairs
2 => [1,2] = 1 pairs
1 => [2] = 0
2 => [] = 0
Sum = 4 pairs
Total = 8
How to find the best segment cost (Finally wrong..)
This method is totally experimental and seems to be correct (but could be totally wrong too ... for now i tested some series and it worked)
I took an other example:
10 3
7 7 2 4 6 9 7 4 1 1
Subsegment 1: I count the number of pairs in all the serie, then i sum each paired value by her key in the array (starting to 0), divide this result by the number of pairs, then round (ceil?) at the closest integrer to find the position (which starting to 1).
Subsegment 2 and 3: I do exactly the same but i excluded the first sub segment.
Total: [7,7,2,4,6,9] [7,4,1] [1] = 1 + 0 + 0 = 1
Testing
I did a little script to generate random values relative to the problem:
var n = document.getElementById('n')
var k = document.getElementById('k')
var s = document.getElementById('s')
var btn = document.getElementById('btn')
// apply random values
function random() {
n.value = Math.ceil(Math.random() * (Math.random()*20)+2)
k.value = Math.ceil(Math.random() * (n.value/3)+1)
var serie = []
for(var i = 0; i<n.value; i++){
serie.push(Math.ceil(Math.random() * (n.value-1)))
}
s.value = serie.join(' ')
}
window.onload = function() { random() }
btn.onclick = function() { random() }
<input id="n" size="2" value="14">
<input id="k" size="2" value="3">
<input id="s" size="40">
<button id="btn">Random</button>
Hope it will help.

Inserteing the elements from several matrices to form a Large matrix in MATLAB [duplicate]

This question already has answers here:
Form a large matrix from n numbers of small matrices
(2 answers)
Closed 8 years ago.
I am a new to MATLAB. I have generated n numbers of smaller matrices of (3 x 1 ) by using a FOR loop. All the matrices are having random values .Now I want to concatenate all the values to form a LARGE matrix 'M'Please check out my codes below .
n= input('please input the number of criterias \n');
for k=1:1:n
fprintf('Please input the %d X %d decision matrix for no %d Criteria \n', n,n,k);
m=input('');
S=sum(m);
for i=1:1:n
for j=1:1:n
m(i,j)= m(i,j)/S(j);
end
end
rS=sum(m,2);
pk=rS/n;
fprintf('the prioritized matrix for no %d criteria ) is ::\n',k);
disp(pk);
end`
and the Command window shows the O/p like this
please input the number of criterias
3
Please input the 3 X 3 decision matrix for no 1 Criteria
[1 2 3 ; 4 5 6; 7 8 9]
the prioritized matrix for no 1 criteria ) is ::
0.1278
0.3333
0.5389
Please input the 3 X 3 decision matrix for no 2 Criteria
[4 5 6; 3 7 9; 8 1 4]
the prioritized matrix for no 2 criteria ) is ::
0.3224
0.4040
0.2736
Please input the 3 X 3 decision matrix for no 3 Criteria
[1 5 4 ; 2 7 0; 3 6 7]
the prioritized matrix for no 3 criteria ) is ::
0.2694
0.2407
0.4899
Now I want to append the values obtained from all the smaller resultant matrices (prioritized matrices) in order to form a LARGE MATRIX 'M'. 'M' shall look like this
M = [ .1278 .3224 .2644 ;
.3333 .4040 .2407 ;
.5839 .2736 .4899 ]
Now Please guide me how could i do this in an efficient way ? NOTE : 'M' is not always a 3X3 matrix , Its a huge order dimension (arround 40X40) in my real project and moreover Its not always fixed and It depends upon the USER INPUT i.e 'n' . I am extremely sorry for the previous Formatting mistakes.
Hard to see what is going on with your loops, but this example should help. Matrix concatenation is done with commas (to add columns) or semi-colons (to add rows). So if you have three row matrices of size 1x3 that look like:
m1=[.1278 .3224 .2644]
m2=[.3338 .4040 .2407]
m3=[.5839 .2736 .4899]
you can make a 3x3 matrix M concatenating your small matrices with semi-colons:
M=[m1;m2;m3]
that looks like this:
M =
0.12780 0.32240 0.26440
0.33380 0.40400 0.24070
0.58390 0.27360 0.48990

Converting a number into a special base system

I want to convert a number in base 10 into a special base form like this:
A*2^2 + B*3^1 + C*2^0
A can take on values of [0,1]
B can take on values of [0,1,2]
C can take on values of [0,1]
For example, the number 8 would be
1*2^2 + 1*3 + 1.
It is guaranteed that the given number can be converted to this specialized base system.
I know how to convert from this base system back to base-10, but I do not know how to convert from base-10 to this specialized base system.
In short words, treat every base number (2^2, 3^1, 2^0 in your example) as weight of an item, and the whole number as the capacity of a bag. This problem wants us to find a combination of these items which they fill the bag exactly.
In the first place this problem is NP-complete. It is identical to the subset sum problem, which can also be seen as a derivative problem of the knapsack problem.
Despite this fact, this problem can however be solved by a pseudo-polynomial time algorithm using dynamic programming in O(nW) time, which n is the number of bases, and W is the number to decompose. The details can be find in this wikipedia page: http://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming and this SO page: What's it called when I want to choose items to fill container as full as possible - and what algorithm should I use?.
Simplifying your "special base":
X = A * 4 + B * 3 + C
A E {0,1}
B E {0,1,2}
C E {0,1}
Obviously the largest number that can be represented is 4 + 2 * 3 + 1 = 11
To figure out how to get the values of A, B, C you can do one of two things:
There are only 12 possible inputs: create a lookup table. Ugly, but quick.
Use some algorithm. A bit trickier.
Let's look at (1) first:
A B C X
0 0 0 0
0 0 1 1
0 1 0 3
0 1 1 4
0 2 0 6
0 2 1 7
1 0 0 4
1 0 1 5
1 1 0 7
1 1 1 8
1 2 0 10
1 2 1 11
Notice that 2 and 9 cannot be expressed in this system, while 4 and 7 occur twice. The fact that you have multiple possible solutions for a given input is a hint that there isn't a really robust algorithm (other than a look up table) to achieve what you want. So your table might look like this:
int A[] = {0,0,-1,0,0,1,0,1,1,-1,1,1};
int B[] = {0,0,-1,1,1,0,2,1,1,-1,2,2};
int C[] = {0,1,-1,0,2,1,0,1,1,-1,0,1};
Then look up A, B, C. If A < 0, there is no solution.

Resources