What does the dot mean in the printf function - c++

I'm solving this problem:
Vanya walks late t night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns.
Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?
In some test it gives WA expected: ** *'22258199.50000*00', found: '22258200.0000000'
but in some tests where answer is not integer, my code output correct answer. (i.e. it can output double)
when I saw the solution there was "printf("%.10f", maxdist/2.)" instead "cout << (double)maxdist/2"
questions:
why doesn't my code work?
What means the dot at the end of "maxdist/2."?
Why there is no "&" before variable maxdist?
#include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
int main(){
int n, l;
cin >> n >> l;
vector<int> v;
for(int i = 0; i < n; i++){
int x;
cin >> x;
v.pb(x);
}
sort(all(v));
int maxdist = 2*max(v[0], l-v[n-1]);
for(int i = 0; i < n-1; i++){
maxdist = max(maxdist, v[i+1] - v[i]);
}
cout << (double)maxdist/2;
}

"%.10f" - means floating value of the variable upto 10 decimal places and "." means the decimal point after which any number followed by f will decide how many decimal places the answer would go.

Related

Find how much xtreme distance two people walk together

Amir and Bond are walking on a street. Initially, both are at the position X=0 and they start walking in the direction of increasing X. After N seconds, they stop. Let's denote Amir's speed and Bond's speed during the i-th of these seconds by Ai and Bi respectively.
Sometimes, Aman and Bond walk together, i.e. with the same speed side by side. Let's define the xtreme distance as the total distance they walk this way. Find this xtreme distance.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
The third line contains N space-separated integers B1,B2,…,BN.
Output
For each test case, print a single line containing one integer ― the total weird distance. It can be proved that this distance is an integer.
Constraints
1≤T≤20
1≤N≤10e5
1≤Ai≤10e5 for each valid i
1≤Bi≤10e5 for each valid i
the sum of N over all test cases does not exceed 10e6
Code
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
while(T--)
{
long long int N;
long long int i, w = 0;
cin >> N;
int * A = new int [N+1];
int * X = new int [N+1];
int * B = new int [N+1];
int * Y = new int [N+1];
Y[0] = 0;
X[0] = 0;
for(i=1;i<=N;i++)
{
cin >> A[i];
X[i] = X[i-1] + A[i];
}
for(i=1;i<=N;i++)
{
cin >> B[i];
Y[i] = Y[i-1] + B[i];
}
for(i=1;i<=N;i++)
{
if((X[i]-X[i-1]) == (Y[i]-Y[i-1]))
w += (Y[i] - Y[i-1]);
}
cout << w << endl;
delete [] A;
delete [] B;
delete [] X;
delete [] Y;
}
return 0;
}
Example Input
3
4
1 3 3 4
1 2 4 4
2
2 3
3 2
2
3 3
3 3
Example Output
5
0
6
Error
I am not able to figure out the error (may be there is error in constraints)

c++ getting a negative value when adding two absolute (positive) values [duplicate]

This question already has answers here:
Adding two positive integers gives negative answer.Why?
(4 answers)
Closed 5 years ago.
I am getting a strange problem. I am getting a negative value when adding two absolute (positive) values. I am trying to solve this exercise from codingame (link: https://www.codingame.com/ide/puzzle/network-cabling).
I tried debugging and I got this:
X[i]: 19715507 X[j]: 938059973 // This one is good
temp: 918344466
Y[i]: 470868309 Y[j]: -816049599 //Something is wrong here
temp: -2089704922
This code is probably not a good solution to the exercise and I will need to improve it, but I still can't figure it out why the value is negative.
Please help.
Thank you.
Code:
int main()
{
int N;
int X[100000];
int Y[100000];
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) { //reading all input
cin >> X[i] >> Y[i]; cin.ignore();
}
int ilgis=0; //ilgis means length
for(int i=0; i<N-1; i++){ //"min" is set to a very high value
//so it could find a lower value later
// "not the best solution"
int min=99999999999999999999; //shortest distance between houses
for(int j=0; j<N; j++){ // here I am trying to find the shortest
// distance from one house to another
if(j!=i){ //I can't count distance from the same house because
// it would be 0
int temp=0;
//counting the distance differently if the
//value is negative or positive
if(X[i]<=0&&X[j]<=0) temp+=abs(abs(X[i])-abs(X[j]));
else if(X[i]<=0&&X[j]>=0) temp+=abs(X[i])+abs(X[j]);
else if(X[i]>=0&&X[j]>=0) temp+=abs(X[i]-X[j]);
else if(X[i]>=0&&X[j]<=0) temp+=(X[i])+abs(X[j]);
//same with y axis
if(Y[i]<=0&&Y[j]<=0) temp+=abs(abs(Y[i])-abs(Y[j]));
else if(Y[i]<=0&&Y[j]>=0) temp+=abs(Y[i])+abs(Y[j]);
else if(Y[i]>=0&&Y[j]>=0) temp+=abs(Y[i]-Y[j]);
else if(Y[i]>=0&&Y[j]<=0) temp+=(Y[i])+abs(Y[j]);
if(min>temp) min=temp;
}
} //if i found the shortesst distance between
//houses I add that value to overall distance
// and continue until all houses are checked
ilgis+=min;
}
cout<<ilgis<<endl;
}
Input of the exercise:
8
-28189131 593661218
102460950 1038903636
938059973 -816049599
-334087877 -290840615
842560881 -116496866
-416604701 690825290
19715507 470868309
846505116 -694479954
The maximum value for int is 2147483647 (which is 2^31-1, assuming int has 32 bits width). You can check it with
std::numeric_limits<int>::max();
You might want to min with this value here. And also use long long as your type for calculations here.

Binary search given slightly inaccurate results

The problem I am trying to solve is the following: I get N rectangular paper strips with 1cm width and length C. I need to cut the strips at a height where the sum of the areas of the cut strip is equal to A. You can see an example bellow for which N = 5, the strips are of length, 5,3,6,2 and 3 cm and A = 3cm where the cut is made at 4cm.
Note that I'm looking here for the red area.
The input is given as follows. The first line in each case begins with two integers N (1 ≤ N ≤ 10^5) and A (1 ≤ A ≤ 10^9) representing respectively the number of strips and the expected resulting area. The next line contains N integers, representing the length C_i (1 <= C_i <= 10^4) of each strip.
The input ends with A = C = 0, which should not be processed.
For each test case, output a single line, the height H of the cut that must be done so that the sum of the area of the cut strips is equal to A cm². Print the answer with 4 decimal places. Output ":D" if no cutting is required, or "-.-" if it’s impossible.
This problem can be found here
My idea for solving this problem was to use a binary search where I pick a height in the middle of the strips and make it larger or smaller depending on whether my cut was too high or too low. My implementation of the problem is given bellow:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;
int main(){
vector<int> v; // Vector that holds paper heights
int n; // Number of papers
double h, // Height of the cut
sum, // Area sum
min_n, // Minimum height for cut to happen
max_n, // Maximum height for cut to happen
a; // Desired final area
// Set desired output
cout << fixed << setprecision(4);
/* Get number of papers and desired area,
terminates if N = A = 0
*/
while(cin >> n >> a && (n||a)){
v.resize(n); // Resize vector to fit all papers
// Get all paper sizes
for(int i=0;i<n;i++){
cin >> v[i];
}
/* Sort the vector in decreasing order to
simplify the search
*/
sort(v.begin(),v.end(),greater<int>());
max_n = v[0]; // Largest possible cut is at the height of the largest paper
min_n = 0; // Smallest possible cut is at the base with height 0
// Iterate until answer is found
while(true){
// Initialize cut height as the average of smallest and largest cut sizes
h = (min_n + max_n)/2;
/* The area sum is equal to the sum of the areas of each cut, which is
given by the height of the paper minus the cut height. If the cut is
higher than the paper, the cut has area 0.
*/
sum = 0;
// Using mascoj sugenstion, a few changes were added
int s; // Temporary variable to hold number of time h is subtracted
for(int i=0; i<n;i++){
if(v[i] <= h) break; // From here onward cut area is 0 and there is no point adding
sum += v[i]; // Removed the subtraction inside of the for loop
s++; // Count how many paper strips were used
}
sum -= h*s // Subtracts the area cut from the s paper strips
// If the error is smaller than the significant value, cut height is printed
if(std::abs(sum-a) < 1e-5){
// If no cut is needed print :D else print cut height
(h < 1e-4 ? cout << ":D" << endl : cout << h << endl);
break;
}
// If max_n is "equal" to min_n and no answer was found, there is no answer
else if(max_n - min_n < 1e-7){
cout << "-.-" << endl;
break;
}
// Reduces search interval
sum < a ? max_n = h : min_n = h;
}
}
return 0;
}
The problem is, after submitting my answer I keep getting a 10% error. The website has a tool for comparing the output of you program with the expected output so I ran a test file with over 1000 randomly generated test cases and when I compared both I got a rounding error on the 4th decimal case, unfortunately, I don't have the file nor the script to generate test cases for me anymore. I tried changing the acceptable error to a smaller one but that didn't work. I can't seem to find the error, does any of you have an idea of what is happening?
ps: Although the problem doesn't say on the description, you can get cuts with fractions as heights
Might be your problem, maybe not: This line is exacerbating floating point error: sum += v[i]-h;
Floating points are only so accurate and compounding this error over a larger summation adds up. I would try using multiplication on h and subtracting that from the total sum of applicable lengths. Should be well within the range of the double precision format so I wouldn't worry about overrunning the format.
Not sure to understand your algorithm but I think that can be done a lot simpler using a map instead a vector.
In the following example the map mp memorize how much (the value) strips are of a given lenght (the key).
An advantage of the map is ordered.
Next you can see how much you have to save (not to cat) and calculate the level of the cut starting from zero, adding 1 when appropriate and adding a fraction when neccessary.
Hope the following example can help
#include <map>
#include <iomanip>
#include <iostream>
int main()
{
int n;
int n2;
int v;
int cut;
int a;
std::map<int, std::size_t> mp;
long long int sum;
long long int ts;
std::cout << std::fixed << std::setprecision(4);
while( (std::cin >> n >> a) && ( n || a ) )
{
mp.clear();
n2 = 0;
sum = 0LL;
for ( auto i = 0 ; i < n ; ++i )
{
std::cin >> v;
if ( v > 0 )
{
sum += v;
++mp[v];
++n2;
}
}
// mp is a map, so the values are ordered
// ts is "to save"; sum of lenghts minus a
ts = sum - a;
// cut level
cut = 0;
// while we can add a full cm to the cut level
while ( (ts > 0LL) && (n2 > 0) && (ts >= n2) )
{
++cut;
ts -= n2;
if ( cut >= mp.cbegin()->first )
{
n2 -= mp.cbegin()->second;
mp.erase(mp.cbegin());
}
}
if ( (ts == 0LL) && (cut == 0) )
std::cout << ":D" << std::endl; // no cut required (?)
else if ( n2 == 0 )
std::cout << "-.-" << std::endl; // impossible (?)
else
std::cout << (cut + double(ts) / n2) << std::endl;
}
}
p.s.: observe that a is defined as an integer in the page that you link.

Simulating a random walk scenario on a 4x4 board

The problem I am working on is as follows. Imagine a 4x4 chess board on top of which you place a king. The probability of you placing the king on each of the squares is one of the inputs (not necessarily the same for all the squares). The king has to make n number of moves (n is an input). The goal is to run an 'experiment' to find the probability after n moves.
My friend solved the problem by creating a general formula using linear algebra. As a challenge/verification of his answer I want to make this program in c++.
We both start with making one generalization. That is since the board is symmetrical we only consider if the king is at a side, corner or middle square of the board.
C S S C
S M M S
S M M S
C S S C
Therefore, we input only P(S_{initial}), P(C_{initial}), P(M_{initial}), the number of moves the king makes, and the number of 'experiments' we make.
The code for my program is below. My results disagreed with my friend's, so I checked my code by setting n to 1 and P(S_{initial}), P(C_{initial}) and P(M_{initial}) to 1/2, 1/4, and 1/4, respectively. By conditional probability I know that P(S)=59/120, P(C)=21/160, P(M)=181/481. My computations do not agree, so I am sure there is a bug or error in my code, but I cannot track it down. I appreciate any help.
Also I know my code is scruffy and inefficient so I appreciate comments about how to improve it. Thanks for your help.
EDIT: To input the initial probabilities I input 2, 1 and 1 for S, C and M, respectively.
EDIT2: Turned out that I used "=" instead of the operator "==" in my if statements. Thank you #Christopher Oicles. Everything works now as expected.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <time.h>
using namespace std;
int S, C, M; //probability 'ratios', i.e. prob of S is S/(S+C+M)
int n; // number of steps
int trials;
int initial(int a,int b,int c); // this 'throws the die' to find where to start and returns 0 for side, 1 for corner, 2 for middle
int step(int a); // this throws the die to make a step and returns the same format
int trial(); //this makes n number of steps, starting at initial(a,b,c) and returns 0,1,2
double data[]={0,0,0}; // the result of the experiment, each element holds the number of times a trial returned the S,C,M where number of s = data[0], I increment this by one every time I run trial();
int main()
{
srand(time(NULL));
for(int i=0;i<3;i++) //reset data array
data[i]=0;
std::cout << "Enter probability ratio of S:";
std::cin >> S;
std::cout << "Enter probability ratio of C:";
std::cin >> C;
std::cout << "Enter probability ratio of M:";
std::cin >> M;
std::cout << "Enter number of steps per trial:";
std::cin >> n;
std::cout << "Enter number of trials:";
std::cin >> trials;
for(int i=0;i<trials;i++)
data[trial()]++;
for(int i=0;i<3;i++)
std::cout << data[i]/trials << " \n";
for(int i=0;i<3;i++)
std::cout<<data[i]<<" ";
cout << "\n \n";
}
int trial(){
int current;// the current place S, C or M or 0,1,2
int next;
current = initial(S,C,M);
for(int i=0;i<n;i++)
{next = step(current);
current = next;}
return current;
}
int initial(int side,int corner,int middle){
int t = rand() % (side+corner+middle); //generates a random number from zero to a+b+c-1
//now we apply the probability
if(t < side)
return 0; //side
if(t >= side && t < (side+corner))
return 1; //corner
if(t>=(side+corner))
return 2; //middle
}
int step(int a){
int t;
switch(a){
case 0: //we are on a side
{t = rand()%5;
if(t < 2){return 0;} //2/5 chance to go to a side
if(t = 2){return 1;} //1/5 chance to go to a corner
if(t > 2){return 2;} //2/5 chance to go to a middle
break;}
case 1: //we are on corner
{t = rand()%3;
if(t < 2){return 0;} //2/3 chance to go to side
if(t = 2){return 2;} //1/3 chance to go to middle
break;}
case 2: //we are on middle
{t = rand()%8;
if(t < 4){return 0;} //1/2 chance go to side
if(t = 4){return 1;} //1/8 chance of corner
if(t > 4){return 2;} //3/8 chance of middle
break;}
}
}

Finding perimeter of a recursively modified square

I have a square of side length 1 . Now, after each second, each square of side L will break into four squares each of side L/2.
I need the compute the total perimeter of the resulting figure, where total perimeter is defined as the sum of lengths of all line segments in the resulting figure. For example, the total perimeter of the image on the left is 4L while that on the right is 6L - 4L from the regular square edges and 2L from the internal line segments.
My code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define mod 1000000007
int main() {
int s;
cin>>s;
long long int ans=4;
for(int i=1;i<=s;i++)
ans+=1<<i;
ans=ans%mod;
cout<<ans<<endl;
return 0;
}
Since the final answer might not fit in a 64-bit signed integer, I am required to compute the answer modulo 1000000007.
For example, after 0 seconds, the length is 4.
After 1 second, the length is 6.
I am not getting the correct output. PLease help
Solve it recursively - let P(L, n) be the "perimeter" of the figure obtained after n iterations, starting with an LxL square. So, P(L, n+1) = 4*P(L/2,n) - 2*L. Also, since the perimeter is linear, P(L/2, n) = P(L, n)/2, giving you P(L,n) = 2*P(L,n-1) - 2*L. Substitute L=1 and run your loop.
int s;
cin>>s;
long long int ans=4;
for(int i=1;i<=s;i++)
{
ans = 2*(ans-1);
ans=ans%mod;
}
The perimeter after s seconds will be : 4+2(2^s-1)
So,
int main()
{
int s;
cout << "Enter Time: ";
cin >> s;
cout << "Perimeter = " << (4 + 2 * (pow( 2, s ) - 1));
}
You have an undivided square. When you split the square into 4 equal squares, you are essentially adding half of the initial perimeter. The outer walls of the original square are included as is in the new perimeter, and add to that the length of the 2 lines drawn inside it, the length of each of which is equal to the side of the square.
noOfsqaures = 1;
oldSide = 1; //one sqaure of side 1
oldPerimeter = 4*oldSide;
loop for the number of seconds
newPerimeter = oldPerimeter + 2*oldSide*noOfSquares
oldSide = oldSide/2; //for the next iteration
oldPermiter = newPermeter //for the next iteration
noOfSquares = noOfSquares*4;
o/p: 4(initial value) +
2 + 4 + 8 + 16 + 32 + ...
I think it would help you for coding. If you need I will give you code
for(int i=1;i<=s;i++)
{
ans+=1<<i;
}