There are N soldiers located on our X-AXIS. The point at which a soldier is located also has some number of bombs.
The war is near and every soldier wants to communicate with every other soldier.
If the i-th soldier has b number of bombs and is located at position X then the cost of communicating with any other soldier j having c number of bombs located at position Y is defined as |X-Y|*max(b,c).
Find the sum of costs of communication if every soldier wants to communicate with every other soldier.
NOTE :- You have to consider pair(i,j) only once in sum of costs.
Input Format:
First line consists of number of test cases T. Each test case consists of three lines. The first line indicates the number of soldiers (N). The second line indicates the coordinates of the N soldiers ( X[i] ). The third line contains the number of bombs at every soldiers location ( B[i] ) . The x-coordinates needn't be in increasing order in the input.
Constraints
1 <= T <= 20 1 <= N <= 200000 1 <= X[i] <= 1000000000 1 <= B[i] <= 10000
Output Format:
The total cost modulo 10^9+7.
Sample Input
1
3
1 3 6
10 20 30
Sample Output
280
Explanation
there are 3 pairs (1,2) -> cost = abs(3-1) * 20 = 40 (1,3) -> cost = abs(1-6) * 30 = 150 (2,3) -> cost = abs(3-6) * 30 = 90 sum = 40 + 150 + 90 = 280
I'm handling modulo (10^9+7) and everything using brute force but getting tle code below its also working for the case above however it one of those annoying tle/type conversion type of problem. Any response is truly appreciated-
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v= x[i]%(Math.pow(10,9)+7)-x[j]%(Math.pow(10,9)+7);
v=Math.abs(v)%(Math.pow(10,9)+7);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
} }
As suggested by #Erwin, don't use Math.pow() to calculate (10^9)+7 thrice in each iteration of the for loop. Instead, take it outside the loop (maybe define it as a constant) and then execute your operations.
Also, you are doing modulo with (10^9)+7 constant twice in your operation. Are you sure that is the intended operation? You are doing it in the first computation of v and then again in the second computation of v. If you need it only for the final cost, you can remove it from the first step.
Here is my code that you can try:
import java.util.*;
public class Main {
public static void main(String args[]) {
double moduloNumber = (Math.pow(10,9)+7);
Scanner sc= new Scanner(System.in);
System.out.print("Enter the Number of Test Cases (1 <= T <= 20): ");
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
System.out.print("\nEnter the Number of Soldiers (1 <= N <= 200000): ");
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
System.out.print("Enter the Position of Soldier " + (i+1) + " (1 <= X[i] <= 1000000000): ");
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
System.out.print("Enter the Number of Bombs with Soldier " + (i+1) + " (1 <= B[i] <= 10000): ");
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v=(x[i]-x[j]);
v=Math.abs(v)%(moduloNumber);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
}
}
I just added some print statements and moved the modulo constant outside the loop to reduce computation costs. You can check if this solves the purpose.
Regards,
AJ
Related
Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}
I have been trying to solve the 3n+1 question in java.However my output seems to be very random. The question is
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then tex2html_wrap_inline44
5. else tex2html_wrap_inline46
6. GOTO 2
Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.
The Input
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j.
You can assume that no operation overflows a 32-bit integer.
The Output
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).
My code is as given below
class CC
{
int c,f,l,m;
int returnCount(int i,int j)
{
f=0;
for(int k=i;k<=j;k++)
{
l=k;
c=0;
while(l>1)
{
if(l%2==0)
{
l=l/2;
c++;
}
else
{
l=3*l+1;
c++;
}
}
if(f<c)
f=++c;
}
return f;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j;
CC obj=new CC();
while(sc.hasNextInt())
{
i=sc.nextInt();
j=sc.nextInt();
System.out.println(i+" "+j+" "+obj.returnCount(i,j));
}}}
Now my Input is
605293 606510
956739 956006
826611 825983
756134 756776
478642 479101
815892 815933
719220 719135
929349 929040
And expected output is
605293 606510 341
956739 956006 352
826611 825983 313
756134 756776 362
478642 479101 338
815892 815933 269
719220 719135 274
929349 929040 339
However my output is
605293 606510 341
956739 956006 0
826611 825983 0
756134 756776 362
478642 479101 338
815892 815933 269
719220 719135 0
929349 929040 0
Please help me find the mistake
The problem is that your in your first line the first number is smaller than the second one, but in the second line the first number is bigger than the second one. You have to switch the numbers or find out the bigger one upfront like that:
import java.util.Scanner;
public class CC {
int c, f, l, m;
int returnCount(int i, int j) {
int smaller = Math.min(i, j);
int bigger = Math.max(i, j);
f = 0;
for (int k = smaller; k <= bigger; k++) {
l = k;
c = 0;
while (l > 1) {
if (l % 2 == 0) {
l = l / 2;
c++;
} else {
l = 3 * l + 1;
c++;
}
}
if (f < c)
f = ++c;
}
return f;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, j;
CC obj = new CC();
while (sc.hasNextInt()) {
i = sc.nextInt();
j = sc.nextInt();
System.out.println(i + " " + j + " " + obj.returnCount(i, j));
}
}
}
The input and output looks then like that:
956739
956006
956739 956006 352
So I was just about finished with a small little program and when I ran it everything worked fine. I did have 1 small technical issue that I didnt like and it was an unevenly spaced "table" if you would. In a nutshell I want it so my outputs are aligned on both sides.
Original output:
How many numbers should be generated?
10
What is the number of values of each random draw?
1000
- 1 108
- 2 90
- 3 101
- 4 98
- 5 117
- 6 97
- 7 89
- 8 111
- 9 93
- 10 96
Code:
import java.util.Random;
import java.util.Scanner;
public class tester
{
public static void main(String[] args)
{
Random rnum = new Random();
Scanner in = new Scanner(System.in);
int x = 0;
int y = 0;
int num = 0;
int length = 0;
System.out.println("How many numbers should be generated?");
x = in.nextInt();
System.out.println("What is the number of values of each random draw?");
y = in.nextInt();
int[] roll = new int[x];
for(int i = 1; i<=y; i++){
num = rnum.nextInt(x);
roll[num] = roll[num] + 1;
}
length = (int) Math.log10(x) + 1;
for(int i = 0; i < x; i++){
System.out.println(i+1 + " " + roll[i]); //This is the code that prints the original output
/*
* This is the code I attempted that did not give the desired result
* a = i;
System.out.println(i+1);
while(Math.log10(i) < length){
System.out.print(" ");
length--;
}
System.out.print(roll[i]);*/
}
}
}
Take a look at the System.out.format (https://docs.oracle.com/javase/tutorial/essential/io/formatting.html) and in perticular the width option. This is probably what you are wanting.
Two ways to go about this:
1) As stated already, look at the System.out.format directory. It has a wide availability of methods to format your output
2) Change the spacing in a manual way, where the spacing depends on the amount of characters in the number to the left.
Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class
package Basics;
import java.util.Scanner;
public class ForLoop {
public static void main(String args[]){
Scanner Jee = new Scanner(System.in);
int Final = 0;
int HowManyRounds = 1;
for (int counter = 1; counter <= HowManyRounds; counter++){
System.out.println("Type your boundary: ");
int Limit = Jee.nextInt();
System.out.println("Type the number which you want the sum of all multiples in given boundary: ");
int number = Jee.nextInt();
System.out.println("Type your starting number: ");
int StartingNumber = Jee.nextInt();
for(int Answer = StartingNumber; Answer <= Limit;Answer += number){
Final += Answer;
}
}
System.out.println(Final);
Jee.close();
}
}
i'm getting wrong answer. i don't know why. when i type 1000 for boundary 5 for round and 0 for starting number, i'm supposed to get 99500 but i'm getting 100500 and when i type for 1000 3 0, i'm getting right answer where as i get same answer for 99 3 0...
Type your boundary:
1000
Type the number which you want the sum of all multiples in given boundary:
5
Type your starting number:
0
100500
Type your boundary:
1000
Type the number which you want the sum of all multiples in given boundary:
3
Type your starting number:
0
166833
Type your boundary:
999
Type the number which you want the sum of all multiples in given boundary:
3
Type your starting number:
0
166833
If you expect an answer of 99500 in the first case, that probably means you don't want to include the limit itself in your operation (which you are doing right now). Try to change the condition in the for loop to answer < limit (instead of <=):
for(int Answer = StartingNumber; Answer < Limit;Answer += number){
[...]
You are not zeroing Final when you start a new loop.
Instead, move the declaration of Final inside the loop:
for (int counter = 1; counter <= HowManyRounds; counter++){
int Final = 0; // now Final is zeroed automatically for every iteration
// rest of loop the same
}
And please adhere to java naming conventions: variables shoiuld start with a lowercase letter, ie int total, not int Total
You seem to having trouble making this work. Here's the whole method fixed, including fixing style issues. Whether the logic is correct, I can't say, because you haven't told us what it is you're actually doing.
private static final int ROUNDS = 3;
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < ROUNDS; i++) {
System.out.println("Type your boundary: ");
int limit = keyboard.nextInt();
System.out.println("Type the number which you want the sum of all multiples in given boundary: ");
int number = keyboard.nextInt();
System.out.println("Type your starting number: ");
int start = keyboard.nextInt();
int total = 0;
for (int n = start; n <= limit; n += number) {
total += n;
}
System.out.println(total);
}
keyboard.close();
}