I am trying to solve http://www.spoj.com/problems/ISLHOP/
The solution I have tried works for the sample input/output but fails the judging process for having the wrong answer.
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
class Main {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int group = 0;
while(in.hasNextLine()) {
int numberOfIsland = in.nextInt();
if(numberOfIsland == 0)
{
break;
}
group++;
in.nextLine();
ArrayList<Island> isl = new ArrayList<Island>();
for(int i = 0; i < numberOfIsland; i++){
String s = in.nextLine();
String[] inputList = s.split("\\s+");
Island newIsland = new Island(Integer.parseInt(inputList[0]),Integer.parseInt(inputList[1]),Integer.parseInt(inputList[2]),-1);
isl.add(newIsland);
}
double result = solve(isl);
System.out.print("Island Group: "+group+" Average ");
System.out.println(String.format("%.2f", result));
}
}
public static double solve(ArrayList<Island> islands) {
TreeSet<Island> islandSet = new TreeSet<Island>();
double time = 0;
islandSet.add(islands.get(0));
Island current;
while(!islandSet.isEmpty()){
current = islandSet.first();
current.queued = true;
islandSet.remove(current);
Island parent = current.parent;
if(parent != null)
{
if(current.parent.curmax < current.curdis)
{
current.curmax = current.curdis;
}
else{
current.curmax = current.parent.curmax;
}
time += current.num * current.curmax;
}
for(int i=0; i< islands.size(); i++)
{
Island next = islands.get(i);
if(!next.queued){
double dis = Math.sqrt(
Math.pow(current.x-next.x,2)
+Math.pow(current.y-next.y,2));
if(islandSet.contains(next))
{
if(next.curdis > dis){
islandSet.remove(next);
next.parent = current;
next.curdis = dis;
islandSet.add(next);
}
}
else{
next.parent = current;
next.curdis = dis;
islandSet.add(next);
}
}
}
}
double total = 0;
for(int i = 0; i < islands.size(); i++)
{
total += islands.get(i).num;
}
return time/total;
}
}
class Island implements Comparable<Island>{
public int x, y, num;
public Island parent;
public double curdis, curmax;
public boolean queued;
public Island(int x, int y, int num, double dis){
this.x = x;
this.y = y;
this.num = num;
this.queued = false;
curdis = 0;
curmax = 0;
}
#Override
public int compareTo(Island o) {
if(curdis > o.curdis)
{
return 1;
}
if(curdis == o.curdis)
{
return 0;
}
return -1;
}
}
class FasterScanner{
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FasterScanner() {
this(System.in);
}
public FasterScanner(InputStream is) {
mIs = is;
}
public boolean hasNext(){
try{
if( read() < 0 )
{
return false;
}
}
catch(InputMismatchException e)
{
return false;
}
return true;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
I tried simply implementing it using Scanner rather than FasterScanner because I couldn't figure out how to write the hasNext() for FasterScanner.
I can't figure out what's wrong with my code as it works for the given sample input.
Does anyone know of a working solution or what is wrong with this one?
Related
I am solving a question on hackerearth and it is successfully compiling and passing when I am using java version Java 8 (oracle 1.8.0_131) but when Java (openjdk 1.7.0_95) is used it gives an error 15: error: cannot infer type arguments for PriorityQueue<> .The error is on the line when mx priority queue is being declared. I want to know how to resolve it and why this error occurs. Here is the code : (note that this question is not part of any ongoing contest) and the relevant part of the code is in main function only.
import java.io.*;
import java.util.*;
class TestClass {
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
int Q=sc.nextInt();
PriorityQueue<Integer> mn=new PriorityQueue<>();
PriorityQueue<Integer> mx=new PriorityQueue<>(Collections.reverseOrder());
int[] cnt =new int[100000+1];
for (int q = 0; q < Q; q++) {
String str=sc.nextLine();
if(str.substring(0,4).equals("Push")) {
int X=Integer.parseInt(str.substring(5));
++cnt[X];
mx.add(X);
mn.add(X);
}
else if (str.equals("Diff")) {
if(mx.isEmpty()||mn.isEmpty())
out.println(-1);
else {
int min = mn.poll();
int max = mx.poll();
if(min==max) {
--cnt[max];
}
else {
--cnt[min];
--cnt[max];
}
mn.remove(max);
mx.remove(min);
out.println(max-min);
}
}
else if (str.equals("CountHigh")) {
if(mx.isEmpty()) {
out.println(-1);
}
else {
out.println(cnt[mx.peek()]);
}
}
else {
if(mn.isEmpty()) {
out.println(-1);
}
else {
out.println(cnt[mn.peek()]);
}
}
// System.out.println(q+" "+mx+" "+mn);
}
out.close();
}
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static int mod = 1000000000+7;
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public double nextDouble() {
return (Double.parseDouble(readString()));
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
In Java 7 there is no PriorityQueue constructor that takes only Comparator as an argument. Take a look Java 7 Priority queue docs. However in Java 8+ there is such constructor for this class.
Your best choice would be to use constructor that takes initial capacity and a Comparator :
PriorityQueue<Integer> mx = new PriorityQueue<Integer>(10, Collections.reverseOrder());
That constructor was added in java-8, so there is no way this would work against 1.7.
There is a feature called target type that was added in java-8, but that is un-related to your question; so it is as simple as adding one more constructor parameter for example, like initial capacity.
PriorityQueue<Integer> mx = new PriorityQueue<>(5, Collections.reverseOrder());
This is my assignment on number 6:
And this is what I have so far. It's not working properly and I am not sure why. Any help would be greatly appreciated. I showed what error I get at the bottom of the code. I'm not sure how to fix it and where to go from here.
import java.util.Arrays;
public class st {
public static void main(String[] args) {
String aa = "8 + (2+2)";
Init init = new Init(aa);
}
}
public final class Init {
public int top = 1;
Integer[] stack = new Integer[10];
String[] queue = new String[10];
int number, x, y, z, op, front, rear;
int finalValue;
int CurrValue;
String queueOperand;
Character s;
public Init(String s) {
ValidateEquation(s);
int finalVal = postFix(s);
System.out.printf("The answer is " + finalVal + "\n");
}
void ValidateEquation(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
push(c);
} else if (c == ')') {
if (isStackEmpty()) {
System.out.printf("Error: Too many ')'");
System.exit(0);
} else {
int closeParen = pop();
}
}
}
}
public int postFix(String s) {
int CurrentCalculation;
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if ((int) c > 47 && (int) c < 58) {
int numVal = Character.getNumericValue(c);
push(numVal);
} else if ((int) c > 41 && (int) c < 48) {
String StrVal = Character.toString(c);
pushQ(StrVal);
}
if (c == '(' || c == ')' || i == s.length()-1) {
String newString = "";
for (Integer stack1 : stack) {
/* iterate through the stack */
if (stack1 != null) {
newString = newString + stack1 + " ";
}
}
for (String queue1 : queue) {
/* iterate through the queue */
if (queue1 != null) {
newString = newString + queue1 + " ";
queueOperand = queue1;
}
}
if (newString.length() > 2) {
int CurrValue = calculateEquation(newString);
if ("+".equals(queueOperand)) {
finalValue = finalValue + CurrValue;
} else if ("-".equals(queueOperand)) {
finalValue = finalValue - CurrValue;
} else if ("*".equals(queueOperand)) {
finalValue = finalValue * CurrValue;
} else if ("/".equals(queueOperand)) {
finalValue = finalValue / CurrValue;
}
popAll();
}
}
i++;
}
return finalValue;
}
int calculateEquation(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((int) c > 47 && (int) c < 58) {
int numVal = Character.getNumericValue(c);
push(numVal);
}
if ((int)c > 41 && (int)c < 48) {
if (s.length() <= 4) {
x = pop();
if (c == '*' || c == '/') {
y = 1;
} else {
y = 0;
}
} else {
x = pop();
y = pop();
}
System.out.println("\n" + x + " " + y + " " + c);
if (c == '+') {
z = x + y;
} else if (c == '-') {
z = x - y;
} else if (c == '*') {
z = x * y;
} else if (c == '/') {
z = x / y;
}
}
}
return z;
}
void push(int x) {
top = top + 1;
/* Increment stack pointer. */
stack[top] = x;
/* Place x on top of stack. */
}
void pushQ(String x) {
rear = rear + 1;
/* Increment stack pointer. */
queue[rear] = x;
/* Place x on top of stack. */
}
int pop() {
int x;
x = stack[top];
/* Retrieve item from top of stack. */
top = top - 1;
/* Decrement stack. */
return x;
}
void popAll() {
Arrays.fill(stack, null);
Arrays.fill(queue, null);
}
boolean isStackEmpty() {
boolean empty;
empty = false;
if (top == -1) {
/* If top = -1, that indicates an empty stack. */
empty = true;
}
return empty;
}
}
This is the error I get:
"/st.java:12: error: class Init is public, should be declared in a file named Init.java
public final class Init {"
You should put each public class in separate file and file name must be class name.
An array has elements(1,2,2,1,1). I have to find the number of distinct elements in the sub array should be equal to the number of distinct elements in the given array i.e the number of distinct elements in the array is 2 (1 and 2).
All the possible subarrays are [1,2] , [1,3] , [1,4] , [1,5] , [2,4] , [2,5] , [3,4] , [3,5]
Distinct means no of distinct elements it 2 {1,2,2} has 2 distinct elements.
In this question 1,4 doesn't mean we are including 1st element and 4th element it means our sub array starts from 1 and end at 4
thus sub array is [1,2,2,1] which has 2 distinct element and it satisfies as the whole array has 2 distinct element.
The problem of the que is that i get test case of array size of 2 lacs and i have to get the output in 1 second and each time i get time limit exceed occurs.
After seeing the answer i have to use buffer reader(instead of scanner {due to performance issue}) and hashmap.
Firstly, i used scanner and buffer reader and both gave output in 2 min 17sec(for 2 lac input). So why there is need to use buffer reader(using scanner reduced the length of the code).
Secondly,i tested both the code on the site and both the code gave output within 1 second whereas in my local machine it took 2 min 17 sec. i didn't understand why there is so much difference.
Third,what is the meaning of this code:
final int mod = (int)1e9+7;
(though i have seen many times when using large number)
Fourth,What is the use of the below code used with the buffered reader.
I am novice in java so pls give simple answer and sorry for the long post
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
class OutputWriter
{
private PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
Answer to your fourth Query : The code is faster than using normal Scanner class.
Hence you can use it in coding competetions.
I made the used the following code on a ~55 MB text file "test.txt".
package so;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class UseIR {
public static void main(String[] args) throws IOException {
//checked using the class provided 'InputReader'
InputReader ob=new InputReader(new FileInputStream(new File("src\\so\\test.txt")));
long str=0;
StringBuilder sb=new StringBuilder();
long curTime=System.currentTimeMillis();
while((str=ob.read())!=-1){
sb.append(((char)str));
}
System.out.println("done "+(System.currentTimeMillis()-curTime));
//checked using the Scanner class
curTime=System.currentTimeMillis();
Scanner s=new Scanner(new File("src\\so\\test.txt"));
sb=new StringBuilder();
while(s.hasNext()){
sb.append(s.next());
}
System.out.println("done "+(System.currentTimeMillis()-curTime));
}
}
With the following Output:
done 447
done 2061
Hope it helps :)
When I attempt to draw the objects in the array it successfully displays them if there is no KeyEvent e in the header, but if KeyEvent e is in the header like is shown (and to my knowledge it needs to be in order to call the method) it does not print anything out.
How can I use the method I created that moves an object in the array if I cannot have KeyEvent e in the header?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Field extends Applet
{
public void paint(Graphics g, KeyEvent e)
{
drawField(g,e);
}
public void drawField(Graphics g, KeyEvent e)
{
int Field[][] = new int[1000][1000];
int Roadl[][] = new int[1000][1000];
Field[100][100] = 1;
Field[100][300] = 2;
Field[100][500] = 3;
Roadl[100][500] = 500;
Field[300][100] = 4;
Roadl[300][100] = 500;
Field[600][600] = 6;
moveCar(Field,600,600,e);
for(int i = 0; i < Field.length; i++)
{
for (int k = 0; k < Field[i].length; k++)
{
if (Field[i][k] == 1)
{
VertBuilding vb1 = new VertBuilding(i,k,g);
}
else if (Field[i][k] == 2)
{
HorizBuilding hb1 = new HorizBuilding(i,k,g);
}
else if (Field[i][k] == 3)
{
VertRoad vr1 = new VertRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 4)
{
HorizRoad hr1 = new HorizRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 5)
{
Coin c1 = new Coin(i,k,g);
}
else if (Field[i][k] == 6)
{
HorizCar car1 = new HorizCar(i,k,g);
}
else if (Field[i][k] == 7)
{
VertCar car1 = new VertCar(i,k,g);
}
}
}
}
public void moveCar(int[][] arr1, int i, int k, KeyEvent e)
{
i += keyTypedH(e);
k += keyTypedV(e);
arr1[i][k] = carD(e);
}
public int keyTypedV (KeyEvent e) {
char c = e.getKeyChar();
int y = 0;
if (c == 's')
{
y+=10;
}
else if (c == 'w')
{
y-=10;
}
return y;
}
public int keyTypedH (KeyEvent e) {
char c = e.getKeyChar();
int x = 0;
if (c == 'a')
{
x-=10;
}
else if (c == 'd')
{
x+=10;
}
return x;
}
public int carD (KeyEvent e) {
char c = e.getKeyChar();
int carLocation = 0;
if (c == 'a')
{
carLocation = 6;
}
else if (c == 'd')
{
carLocation = 6;
}
else if (c == 's')
{
carLocation = 7;
}
else if (c == 'w')
{
carLocation = 7;
}
return carLocation;
}
}
Yes I want to start programming competitions so I dont know how to submit in Java?
Answers very apreciated
bye
i have been in a lot of contests:
/** #team=civilian */
import java.io.*;
import java.math.*;
import java.util.*;
public class _template {
static BufferedReader input;
static StringTokenizer _stk;
static String readln() throws IOException {
String l = input.readLine();
if (l != null)
_stk = new StringTokenizer(l, " ");
return l;
}
static String next() {
return _stk.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static PrintWriter output = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
input = new BufferedReader(new InputStreamReader(System.in));
// input = new BufferedReader(new FileReader("_template"));
// output.print("ja");
// output.close();// Be sure to close the output at the end
//or maybe he does not print everything.
}
}
Some think is best to compite in c++:
//
#include <bits/stdc++.h>
#define D(x) cout << #x << " = " << (x) << endl;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long int64;
const int INF = (int)(1e9);
const int64 INFLL = (int64)(1e18);
const double EPS = 1e-13;
int main() {
#ifdef LOCAL
freopen(".in.txt", "r", stdin);
freopen(".out.txt", "w", stdout);
#else
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#endif
}
and this help when you are practicing:
#createfiles.sh
function createfiles {
cp path/_template.cpp ./"$1.cpp";
touch "$1.in.txt";
touch "$1.out.txt";
sed "s/.in.txt/$1.in.txt/" < "$1.cpp" > "tmp";
sed "s/.out.txt/$1.out.txt/" < "tmp" > "$1.cpp" ;
rm tmp;
}
createfiles $1
runing test:
#compile_cpp.sh
function compile_cpp {
g++ -o "${1::-4}_exe" -DLOCAL "$1";
./"${1::-4}_exe";
}
compile_cpp $1
and you run it like this:
$ bash createfiles.sh uva12520
# you program an awesome solution
# and you test it
$ bash compile_ccp.sh uva12520.cpp
i think is best to create an alias in your .bash like
alias compile_cpp_maraton='function fun() { bash /path/my_commands/compile_cpp_maraton.sh "$1"; }; fun'
Sorry for the long post.
Here is a template mentioned in FlatFoot Codeforces user blog http://codeforces.com/blog/entry/7018
public class Main{
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// Start writing your solution here. -------------------------------------
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
int result = 3*n;
out.println(result); // print via PrintWriter
*/
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
I do not know about CF but you can try this at SPOJ. Have a look at examples here
Have a look at it,you might find your answer here :
http://rgpv.ac.in/Campus/CodeForce%20Tutorial.pdf
Java syntax :
import java.util.*;
public class Prime {
public static void main(String args[]) {
int i;
Scanner in = new Scanner(System.in);
i = in.nextInt();
/* Take input from standard input */
if (isprime(i)) {
System.out.println("YES");
/*
* Print outp ut on standard output
*/
} else {
System.out.println("NO");
/* Print output on standard output */
}
}
public static boolean isprime(int a) {
for (int i = 2; i < a; i++) {
if (a % i == 0)
return false;
}
return true;
}
}
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* Author: o_panda_o
* Email: emailofpanda#yahoo.com
*/
public class Main{
static class ProblemSolver{
public void solveTheProblem(InputReader in,OutputWriter out){
/**
* This template is used by many coders for fast IO
*
* This portion acts as the main method we use. Everything we need to code...
* ...can be written here without even touching the main method.
*
* Following are the examples for IO and for more information have a look...
* ...on the classes InputReader(for Fast Input) and OutputWriter(for Fast...
* ...Output). The methods there are self explanatory
*/
/**
* How to take inputs:
* - Taking input is just nearly similar to the way we take input using scanner in Java.
* - e.g. int n=in.nextInt(); long n=in.nextLong();
*/
/**
* How to print output:
* - It is just like we use PrintWriter. Instead of using System.out, we can...
* ...only use out in that place.
* - e.g. out.print(), out.println() etc.
*/
}
//You can add necessary methods here also. Uncomment the code and test it above
//public int add(int a,int b){
// return a+b;
//}
}
//Everything below you see is a template for every code. You don't need to change them most of the time.
//As you go on coding, in the time of need you will realise what you need to change when. Just trust me on this.
public static void main(String[] args){
InputStream inputStream=System.in;
OutputStream outputStream=System.out;
InputReader in=new InputReader(inputStream);
OutputWriter out=new OutputWriter(outputStream);
ProblemSolver problemSolver=new ProblemSolver();
problemSolver.solveTheProblem(in,out);
out.flush();
out.close();
}
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n){
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n){
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n){
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n){
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n){
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n){
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(double[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void println(double[] array) {
print(array);
writer.println();
}
public void println(long[] array) {
print(array);
writer.println();
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void println(char i) {
writer.println(i);
}
public void println(char[] array) {
writer.println(array);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
public void separateLines(int[] array) {
for (int i : array) {
println(i);
}
}
}