I'm retrying the USACO Silver Problem Robot Instructions.
On my computer (Macbook Air M1 2020, MacOS Big Sur version 11.3.1), when I manually input the sample case my program outputs the correct answer. However, on the USACO grading server, it displays:
The following appeared on standard error:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at RobotInstructions.main(RobotInstructions.java:33)
For reference, my current code is:
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Math;
public class RobotInstructions {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nInstructions = in.nextInt();
int wontx = in.nextInt();
int wonty = in.nextInt();
ArrayList<int[]> a;
ArrayList<int[]> b;
int n1;
int n2;
if (nInstructions%2==0) {
n1 = (int) nInstructions/2;
n2 = (int) nInstructions/2;
} else {
n1 = ((int) (nInstructions-1)/2);
n2 = ((int) (nInstructions+1)/2);
}
/////////////////////////////////
Scanner in1 = new Scanner(System.in);
int[][] instructionList = new int[n1][2];
for (int i = 0; i<n1; i++) {
int a1 = in1.nextInt();
int b1 = in1.nextInt();
instructionList[i][0] = a1;
instructionList[i][1] = b1;
}
a = subset(n1, instructionList);
/////////////////////////////////
/////////////////////////////////
int[][] instructionList1 = new int[n2][2];
for (int i = 0; i<n2; i++) {
int a1 = in1.nextInt();
int b1 = in1.nextInt();
instructionList1[i][0] = a1;
instructionList1[i][1] = b1;
}
b = subset(n2, instructionList1);
/////////////////////////////////
int[] answers = new int[nInstructions];
for (int[] i : a) {
for (int[] j : b) {
if (i[0]+j[0]==wontx && i[1]+j[1]==wonty) {
answers[i[2]+j[2]-1]++;
}
}
}
for (int i : answers) {
System.out.println(i);
}
}
public static ArrayList<int[]> subset(int n, int[][] instructionList) {
ArrayList<int[]> sums = new ArrayList<int[]>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i< (Math.pow(2,n)) ; i++) {
sb.setLength(0);
String a = Integer.toBinaryString(i);
for (int j = 0; j<(n-a.length()); j++) {
sb.append("0");
}
sb.append(a);
String c = sb.toString();
int x = 0;
int y = 0;
int amt = 0;
for (int k = 0; k<n; k++) {
if (c.charAt(k) == '1') {
x += instructionList[k][0];
y += instructionList[k][1];
amt++;
}
}
int[] m = new int[] {x,y,amt};
sums.add(m);
}
return sums;
}
}
I would not like any feedback on the efficiency of my program, just the reason why the grading server doesn't like my input format.
Problem Statement:
While playing an RPG game, you were assigned to complete one of the hardest quests in this game. There are n monsters you'll need to defeat in this quest. Each monster i is described with two integer numbers - poweri and bonusi. To defeat this monster, you'll need at least poweri experience points. If you try fighting this monster without having enough experience points, you lose immediately.
You will also gain bonusi experience points if you defeat this monster. You can defeat monsters in any order. The quest turned out to be very hard - you try to defeat the monsters but keep losing repeatedly. Your friend told you that this quest is impossible to complete. Knowing that, you're interested, what is the maximum possible number of monsters you can defeat?
Input:
The first line contains an integer, n, denoting the number of monsters.
The next line contains an integer, e, denoting your initial experience.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, poweri, which
represents power of the corresponding monster.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, bonusi, which represents bonus for defeating the corresponding monster.
Sample cases:
Input 2 123 78 130 10 0
Output 2
Output description
Initial experience level is 123 points.
Defeat the first monster having power of 78 and bonus of 10. Experience level is now 123+10=133.
Defeat the second monster.
What I have tried:
public static int defeat(int [] monster,int bonus[],int n,int exp){
if(n==0)
return 0;
if(n==1 && monster[0]<=exp)return 1;
if(n==1 && monster[0]>exp) return 0;
if(monster[n-1]<=exp){
return defeat(monster,bonus,n-1,bonus[n-1]+exp )+ defeat(monster,bonus,n-1,exp);
}else{
return defeat(monster,bonus,n-1,exp);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int exp = s.nextInt();
int monst[] = new int[n];
int bonus[] = new int[n];
for (int i = 0; i < n; i++) {
monst[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
bonus[i] = s.nextInt();
}
System.out.println(defeat(monst,bonus,n,exp));
}
I am not getting correct answers with this solution.
I thought of this problem as 0/1 knapsack problem( correct me If I am wrong). Also can you provide me DP solution of this problem.
You can just sort the monsters from lowest to highest power required and defeat them in that order.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int exp = s.nextInt();
int monst[] = new int[n];
int bonus[] = new int[n];
for (int i = 0; i < n; i++) {
monst[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
bonus[i] = s.nextInt();
}
class Monster {
private final int power, bonus;
public Monster(int power, int bonus){
this.power = power;
this.bonus = bonus;
}
}
Monster[] monsters = new Monster[n];
for(int i = 0; i < n; i++) monsters[i] = new Monster(monst[i], bonus[i]);
Arrays.sort(monsters, Comparator.comparingInt(m -> m.power));
int count = 0;
for(Monster m: monsters){
if(exp < m.power) break;
exp += m.bonus;
++count;
}
System.out.println(count);
}
Perhaps I am too simplistic, but I would try it as below:
First create a class Monster like this:
public class Monster
{
final int m_Power;
final int m_Bonus;
public Monster( final int power, final int bonus )
{
m_Power = power;
m_Bonus = bonus;
}
public final int getPower() { return m_Power; }
public final int getBonus() { return m_Bonus; }
}
Next, initialise a list of Monsters like this:
public static void main( String... args )
{
final var scanner = new Scanner( System.in );
final var n = scanner.nextInt();
final var experience = scanner.nextInt();
final var power [] = new int [n];
for( var i = 0; i < n; ++i )
{
power [i] = scanner.nextInt();
}
List<Monster> monsters = new ArrayList<>( n );
for( var i = 0; i < n; ++i )
{
monsters.add( new Monster( power [i], scanner.nextInt();
}
monsters.sort( (m1,m2) ->
{
final var p = m1.getPower() - m2.getPower();
return p == 0 ? m2.getBonus() - m1.getBonus(() : p;
} ); //*1
System.out.println( defeat( monsters, experience ) );
}
*1 -> this implementation of the comparator works well only for power and bonus values that are small compared to MAX_INT.
The list monsters now contains the monsters sorted by their power in ascending order; monsters with the same power are ordered by their bonus values in descending order.
Now my implementation of defeat() would look like this:
public final int defeat( final List<Monster> m, final int initialExperience )
{
var experience = initialExperience;
var retValue = 0;
final Stack<Monster> monsters = new LinkedList<>( m );
while( !monsters.empty() )
{
var monster = monsters.pop();
if( experience > monster.getPower() )
{
experience += monster.getBonus();
++retValue;
}
else break;
}
return retValue;
}
n=int(input())
e=int(input())
P=[]
for i in range(n):
P.append(int(input()))
B=[]
for i in range(n):
B.append(int(input()))
c=0
f=True
while n>0 and f:
f=False
i=0
while i<n:
if e>=P[i]:
e+=B[i]
P.pop(i)
B.pop(i)
n-=1
c+=1
f=True
i-=1
i+=1
print(c)
import java.io.*;
import java.util.*;
class Player {
int exp;
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
}
class Monster {
int power;
int bonus;
public int getPower() {
return this.power;
}
public int getBonus() {
return this.bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
public void setPower(int power) {
this.power = power;
}
}
class Calc {
public int calc() {
Scanner sc = new Scanner(System.in);
//number of monsters
System.out.println("enter the number of monsters");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("enter the power of the player");
Player player = new Player();
player.setExp(sc.nextInt());
//declaration of array type object of monster
Monster monster[] = new Monster[n];
//value setting completed
for (int i = 0; i < n; i++) {
//allocation of object to the real
monster[i] = new Monster();
System.out.println("enter the power of monster");
monster[i].setPower(sc.nextInt());
System.out.println("enter the bonus that to be earned after killing the monster");
monster[i].setBonus(sc.nextInt());
}
//calculate win or loose
int count = 0;
int flag = 0;
//**
for (int i = 0; i < n; i++) {
if (player.getExp() >= monster[i].getPower()) {
player.setExp(player.getExp() + monster[i].getBonus());
count = count + 1;
// flag = flag + 1;
} else if (player.getExp() < monster[i].getPower()) {
for (int j = 0; j < n; j++)
arr[j] = i;
//count = count;
flag = flag + 1;
}
//**
for (int t = 0; t < flag; t++) {
if (player.getExp() >= monster[arr[t]].getPower()) {
count = count + 1;
}
}
}
return count;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println("welcome to the loosing game");
Calc c = new Calc();
System.out.println("no of monster killed" + c.calc());
}
}
#include<bits/stdc++.h>
using namespace std;
struct Monsters
{
int power;
int bonus;
};
class Solution
{
public:
//Function to find the maximum number of activities that can
//be performed by a single person.
static bool compare(Monsters a, Monsters b)
{
if(a.power < b.power) return 1;
else if(a.power > b.power) return 0;
else return 1;
}
int MonstersKill(vector<int> power, vector<int> bonus, int n, int exp)
{
Monsters arr[n];
for(int i = 0; i < n; i++)
{
arr[i].power = power[i];
arr[i].bonus = bonus[i];
}
sort(arr, arr+n, compare);
int count = 0;
for(int i = 0; i < n; i++)
{
if(arr[i].power <= exp)
{
count++;
exp += arr[i].bonus;
}
else
break;
}
return count;
}
};
int main()
{
int n, exp;
cin >> n >> exp;
vector<int> power(n), bonus(n);
//adding elements to arrays power and bonus
for(int i=0;i<n;i++)
cin>>power[i];
for(int i=0;i<n;i++)
cin>>bonus[i];
Solution ob;
cout << ob.MonstersKill(power, bonus, n, exp) << endl;
return 0;
}
Time Complexity : O(N * Log(N))
Auxilliary Space: O(N)
import java.util.Scanner;
class codeabbey145
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
double A = 0;
double B = 0;
double M = 0;
System.out.println("\n\nHow many sets?");
int s = input.nextInt();
double X[] = new double[s];
for(int i = 0; i<s; i++)
{
System.out.println("A: ");
A = input.nextDouble();
System.out.println("B: ");
B = input.nextDouble();
System.out.println("M: ");
M = input.nextDouble();
X[i] = (Math.pow(A, B)) % M; //(A^B)%M
}
for(int j = 0; j<s; j++)
{
System.out.print(Math.round(X[j]) + " ");
}
}
}
I have been attempting to complete Exercise 145 on Codeabbey.com
The formula given for modular exponentiation is: (A^B)%M
I tried my best to implement this formula into my code, but the answers I have been getting are incorrect. Anybody know why this might be?
Thanks in advance
You code is Absolutely correct : Check here .
Probably you should use BigInteger: for handling large numbers , double is never recommended.
Here is the working example: check this live demo
Code
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("\n\nHow many sets?");
int s = input.nextInt();
BigInteger[] X = new BigInteger[s];
for (int i = 0; i < s; i++) {
System.out.println("A: ");
BigInteger A = input.nextBigInteger();
System.out.println("B: ");
BigInteger B = input.nextBigInteger();
System.out.println("M: ");
BigInteger M = input.nextBigInteger();
X[i] = A.modPow(B, M); //(A^B)%M
}
for (int i = 0; i < X.length; i++) {
System.out.println(X[i]);
}
}
I have attempted this question on CodeAbbey.
My solution was accepted.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
int s = input.nextInt();
BigInteger[] X = new BigInteger[s];
for (int i = 0; i < s; i++) {
BigInteger A = input.nextBigInteger();
BigInteger B = input.nextBigInteger();
BigInteger M = input.nextBigInteger();
X[i] = A.modPow(B, M);
}
for (int i = 0; i < X.length; i++) {
System.out.println(X[i]+" ");
}
}
}
Most likely the values are too big to fit into a double, so they overflow. Your best bet is probably to implement using BigInteger objects.
BigInteger has pow and mod functions that you can use for your calculations.
I've been trying to solve this rather easy problem on SPOJ: http://www.spoj.com/problems/HS08PAUL/.
It requires the number of prime numbers (less than n) which can be expressed in the form x^2+y^4 (where x and y are integers) to be found out.
I've whipped up a brute force solution which takes up quite a while for (n ~= 1000000), resulting in a TLE (time limit exceeded) error being thrown by the engine. Here's the source code:
import java.io.*;
import java.util.*;
class HS08PAUL {
public static int[] sieve(int n){
boolean[] prime = new boolean[n+1];
int[] primeNumbers = new int[n];
int index = 0;
Arrays.fill(primeNumbers, 0);
Arrays.fill(prime,true);
prime[0] = false;
prime[1] = false;
int m = (int)Math.sqrt(n);
for(int i = 2; i <= m; i++){
if(prime[i])
for(int k = i*i; k<=n; k+=i)
prime[k] = false;
}
for(int j = 2; j <= n; j++) {
if(prime[j]) {
primeNumbers[index] = j;
index++;
}
}
return primeNumbers;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
double numberOfTestCases = in.nextDouble();
while(numberOfTestCases -- > 0) {
int index = 0, y = 0, count = 0;
int num = in.nextInt();
int[] primes = sieve(num);
while(index < num/3 ) {
for(y = 1; y < 57 ; y ++) {
if(Math.ceil(Math.sqrt(primes[index] - Math.pow(y,4))) == Math.floor(Math.sqrt(primes[index] - Math.pow(y,4)))) {
count++;
break;
}
}
index++;
}
System.out.println(count);
}
}
catch(Exception e) {
}
}
}
Is there a way in which I can make this approach work?
P.S.:Please ignore the unruly exception handling.
How many numbers of the form x^2+y^4 are there below 1000000? How many prime numbers are there below 1000000? What do these two numbers tell you about how you should approach the solution?
#isnot2bad's comment is also relevant.
I am calling one array and returning another array that is sorted based on the other array.
I think my method is proper but when I try to print out from the new array in the main method i'm getting an error that reads,
"Cannot resolve B to a variable."
B is the name of the new array that my method should return.
Thanks in advance.
package sort;
public class SortByFinal {
public static int [][] sortByFinal(int n, int [][] A)
{
int [][]B = new int [n][3];
int max = 0;
for(int i =0; i<n; i++)
{
for(int j = i; j<n; j++)
{
max = Math.max(A[i][1], max);
}
for(int k = i; k<n; k++)
{
if(A[k][1] == max)
{
B[k][0] = A[k][0];
B[k][1] = A[k][1];
B[k][2] = A[k][2];
}
}
}
return B;
}
public static void main(String []args)
{
int num = 5;
int[][] now = new int [num][3];
now[0][0] = 2342;
now[0][1] = 88;
now[0][2] = 98;
now[1][0] = 3901;
now[1][1] = 75;
now[1][2] = 71;
now[2][0] = 1444;
now[2][1] = 60;
now[2][2] = 85;
now[3][0] = 5327;
now[3][1] = 95;
now[3][2] = 80;
now[4][0] = 4888;
now[4][1] = 83;
now[4][2] = 100;
//int [][] B = new int[num][3];
sortByFinal(num, now);
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(B[i][j]);//this gives me the "B cannot be resolved to a variable."
System.out.print(" ");
}
System.out.println();
}
}
}
B is defined in sortByFinal(), but not in main(). To fix this, you could change your main to the follow:
int[][] B = sortByFinal(num, now);
Since sortByFinal(num, now) returns a int[][], this will work.
In your code, you're calling the function, but not doing anything with the return value, and you do not have access to the local variables of other methods; hence, the message.