I'm trying to solve this problem of SPOJ: http://br.spoj.com/problems/GENERAL/
My solution works in Ideone (http://ideone.com/Xj2B9Y), but when I put the same solution in SPOJ, it reports that TLE - Time Limit Exceeded.
I have searched in the Internet to find a solution to improve my code. I replaced the "Scanner" by "BufferedReader", but I keep getting the message TLE.
Please could someone tell me where I am going wrong?
public static void main(String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//Scanner scan = new Scanner(System.in);
int instancias = Integer.parseInt(br.readLine());
int count = 0;
while(instancias != 0)
{
count = 0;
boolean possible = true;
boolean impossible = false;
st = new StringTokenizer(br.readLine());
int numSoldados = Integer.parseInt(st.nextToken());
int distancia = Integer.parseInt(st.nextToken());
int[] listaSoldados = new int[numSoldados];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < numSoldados; i++)
{
listaSoldados[i] = Integer.parseInt(st.nextToken());
}
while(possible)
{
possible = false;
for (int i = 0; i < numSoldados; i++)
{
if(numSoldados - (i + distancia) >= 1)
{
int alturaPS = listaSoldados[i];
int alturaSS = listaSoldados[i + distancia];
if(alturaPS > alturaSS)
{
listaSoldados[i] = alturaSS;
listaSoldados[i + distancia] = alturaPS;
count = count + 1;
possible = true;
}
}
else
{
if(!possible)
{
for (int j = 0; j < numSoldados - 1; j++)
{
if(listaSoldados[j] > listaSoldados[j+1])
{
impossible = true;
break;
}
}
break;
}
break;
}
}
}
if(impossible)
System.out.println("impossivel");
else
System.out.println(count);
instancias--;
}
}
Related
I am attempting to read in info from files to implement Dijkstra's algorithm. I believe that the double for loop is causing this to drastically slow down, is there anyway around this?
Edge[] edge = new Edge[127807];
int indexEdge = 0;
String line2 = "";
BufferedReader fileReader2 = new BufferedReader(new FileReader("Road.txt"));
String valueString = null;
String vertex1IDName = null;
String vertex2IDName = null;
String extra = null;
float value = 0;
int vertex1ID = 0;
int vertex2ID = 0;
//Read the file line by line
while ((line2 = fileReader2.readLine()) != null)
{
//Get all tokens available in line
String[] tokens2 = line2.split(DELIMITER);
for(String token1 : tokens2)
{
vertex1IDName = tokens2[0];
vertex2IDName = tokens2[1];
valueString = tokens2[2];
if(tokens2.length - 1 == 3) {
extra = tokens2[tokens2.length - 1];
}
else {
extra = "";
}
vertex1ID = Integer.parseInt(vertex1IDName);
vertex2ID = Integer.parseInt(vertex2IDName);
value = Float.parseFloat(valueString);
}
System.out.println("value: "+ value + " vertex1ID:"+ vertex1ID +" vertex2ID:"+ vertex2ID+ " extra:" + extra);
//if vertex 1 name or vertex 2 name in vertex.getID()
for(int i = 0; i< indexVertex; i++) {
for(int j = 0; j< indexVertex; j++) {
if(vertex1ID == vertex[i].getID() && vertex2ID == vertex[j].getID()) {
vertex[i].addNeighbour(edge[indexEdge] = new Edge(value,vertex[i],vertex[j],extra));
indexEdge++;
}
}
}
}
I am new in java. Firstly, I'm sorry for my English. I wrote a code to merge two different txt files in the mergedFile.txt with determined data from the data1.txt and data2.txt. I create 5 different arrays to use them better but I cannot learn the length of words in the textfiles so arrays are using determined parameter. If I want to add another student, this codes don't work. Can you help me?
data1.txt
ID,Name,LastName,Department
12345,John,Samon,Computer Science
14524,David,Souza,Electric and Electronic
.
.
data2.txt
ID,Q1,Q2,Q3,Midterm,Final
12345,100,90,75,89,100
14524,80,70,65,15,90
.
margedFile.txt
ID,Name,Q_Average,Midterm,Final,Department
12345,John,88.3,89,100,Computer Science
14524,David,67.0,100,70,Electric and Electronic
This is ReadData Class
import java.io.FileInputStream;//import java.io library
import java.util.Scanner;//import scanner library
public class ReadData {
public static String[] Read(String filename,String filename2) {
Scanner scan = null;
Scanner scan1 = null;/
FileInputStream input1 = null;
FileInputStream input = null;
String[] result = new String[3];
try {
input = new FileInputStream(filename);
scan = new Scanner(input);
input1 = new FileInputStream(filename2);
scan1 = new Scanner(input1);
String[][] myArray = new String[4][4];
String[][] myArray1 = new String[4][6];
while(scan.hasNext() || scan1.hasNext()) {
for (int i = 0; i < myArray.length; i++) {
String[] split =
scan.nextLine().trim().split(",");
for (int j = 0; j < split.length; j++)
{
myArray[i][j] = split[j];
}
}
for (int i = 0; i < myArray1.length; i++) {
String[] split1 = scan1.nextLine().trim().split(",");
for (int j = 0; j < split1.length; j++) {
myArray1[i][j] = split1[j];
}
}
}
int[][] quiz = new int[3][3];
double[] average = new double[3];
int sum = 0;
double averagee = 0;
for (int i = 0; i < quiz.length; i++) {
for (int j = 0; j < quiz.length; j++) {
quiz[i][j] = Integer.parseInt(myArray1[i+1][j+1]);
sum += quiz[i][j];
}
averagee = sum/quiz.length;
average[i] = averagee;
sum = 0;
}
for (int i = 1; i < myArray1.length; i++) {
for (int j = 1; j < myArray1.length; j++) {
if(myArray[i][0].equalsIgnoreCase(myArray1[j][0])) {
result[i-1] = "\n" + myArray[i][0] + " "+ myArray[i][1] + " " + (average[j-1]) +" "+ myArray1[j][4] +" " + myArray1[j][5] + " "+ myArray[i][3];
//System.out.println(Arrays.deepToString(myArray[i]) + " " + Arrays.deepToString(myArray1[j]));
}
}
}
//System.out.println(Arrays.deepToString(quiz));
//System.out.println(Arrays.toString(average));
}
catch(Exception e) {
System.out.println(e);
}
return result;
}
}
This is WriteData class
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class WriteData extends ReadData {
void Write(String filename) {
PrintWriter writer = null;
FileOutputStream output = null;
try {
output = new FileOutputStream(filename);
writer = new PrintWriter(output);
writer.print("ID,Name,Q_Average,Midterm,Final,Department ");
writer.print(Arrays.toString(Read("data1.txt",
"data2.txt")));
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
I want to implement my input reading method into my main class, I want use my code to parse. It's been fixed now. thanks.
String x;
int count = -1;=
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
}
private List<String[]> termsDocsArray = new ArrayList<String[]>();
private List<String> allTerms = new ArrayList<String>(); //to hold all terms
private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
/**
To start with your code
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
should be in it's own method like .
private void doSomething(){
//This variable will hold all terms of each document in an array.
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
Secondly in ur given code u have written like
int count = -1;=
which accounts to this error Syntax error on token "=", { expected.It should be
int count = -1;
And since all your code is simply written in class without any method so it is giving you the error saying { expected.
Please make sure you have copied the code correctly.
I have the following little problem... I have this code that uses the method OpenFile() of one class ReadData to read a .txt file and also I have another class ArraysTZones used to create an object that stores 3 arrays (data1,data2,data3) and 3 integers (total1,total2,total3) returned by the method OpenFile(). The problem is that when I try to display each array (data1,data2,data3) using the method getArray() of ArrayTZones it stops and displays the error NullPointerException. Anyone knows how could I fix this?
public static void main (String args[]) throws IOException {
String fileName = ".//data.txt";
int[] def = new int[180];
try {
ReadData file = new ReadData(fileName);
ArraysTZones summaryatz = new ArraysTZones();
summaryatz = file.OpenFile();
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray1()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal1());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray2()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal2());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray3()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal3());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
Heres OpenFile()
public ArraysTZones OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfTimeZones = 3;
int[] data1 = new int[180];
int[] data2 = new int[180];
int[] data3 = new int[180];
int total1 = 0;
int total2 = 0;
int total3 = 0;
ArraysTZones atz = new ArraysTZones();
for (int i = 0; i < numberOfTimeZones; i++){
if (i == 0) {
String firstTimeZone = textReader.readLine();
String[] val = firstTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total1 += stats;
data1[u] = stats;
}
total1= total1/180;
atz.setTotal1(total1);
atz.setArray1(data1);
}
else
if (i == 1) {
String secondTimeZone = textReader.readLine();
String[] val = secondTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total2 += stats;
data2[u] = stats;
}
total2= total2/180;
atz.setTotal2(total2);
atz.setArray2(data2);
}
else {
String thirdTimeZone = textReader.readLine();
String[] val = thirdTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total3 += stats;
data3[u] = stats;
}
total3= total3/180;
atz.setTotal3(total3);
atz.setArray3(data3);
}
}
textReader.close();
return atz;
}
The getArray()
public int[] getArray1 () {
return data1;
}
And setArray()
public void setArray1 (int[] farray) {
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
The problem seems to be here
public void setArray1 (int[] farray)
{
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
You're declaring a new variable called data1 and storing the content of farray to it.
After that method is done, that variable will be removed, due to his scope.
Remove int[] from the line int[] data1 = new int[180]; (or just remove the whole line .. it is unnecessary) and your data will be stored in the correct variable that was declared for the class.
public void setArray1 (int[] farray) {
data1 = farray;
}
You have to initialize ArraysTZones
The following problem appears in my console after I execute the code and introduce the first cota l[i].cota = sc.nextLine();
Exception in thread "main" java.lang.NullPointerException
at exercicio6.introlivros(exercicio6.java:18)
at exercicio6.main(exercicio6.java:9)
can anyone tell me what's the issue?
Here is my code
public class exercicio6 {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
livro l[] = new livro[200];
l = introlivros();
apagarbase(l);
}
public static livro[] introlivros() {
int i = 0;
livro l[] = new livro[200];
do {
System.out.print("Introduza a cota:");
l[i].cota = sc.nextLine();
if (l[i].cota.length() == 0)
break;
do {
System.out.print("Introduza o autor:");
l[i].autor = sc.nextLine();
} while (l[i].autor.length() < 40);
System.out.print("Introduza o titulo:");
l[i].titulo = sc.nextLine();
System.out.println("Introduza a data:");
System.out.println("Dia:");
l[i].data[0] = sc.nextInt();
System.out.println("Mes:");
l[i].data[1] = sc.nextInt();
System.out.println("Ano:");
l[i].data[2] = sc.nextInt();
i++;
} while (i < 200);
return l;
}
public static void remover(livro l[]) {
String cota1 = new String();
boolean verificar = false;
do {
cota1 = sc.nextLine();
if (cota1.length() != 0) {
for (int i = 0; i < 200; i++) {
if (cota1 == l[i].cota) {
l[i].cota = "";
break;
}
if (cota1 != l[i].cota) {
verificar = true;
}
}
}
if (cota1.length() == 0) {
System.out.println("Introduza a cota de novo!");
}
if (verificar == true) {
System.out.println("Esse livro não eciste!");
}
} while (cota1.length() == 0);
}
public static void apagarbase(livro l[]) {
livro p[] = new livro[200];
for (int i = 0; i < 200; i++) {
l[i].cota = null;
l[i].autor = null;
l[i].titulo = null;
l[i].data[0] = 0;
/*
* l[i].data[1]=null; l[i].data[2]=null; l[i].estado[0]=null;
*/
}
}
}
class livro {
String cota = new String();
String autor = new String();
String titulo = new String();
int data[] = new int[3];
char estado[] = new char[1]; // Requisitado R, Livre L, Condicionado C;
}
As stated above - objects are initialized to null
A quick way of populating an array is -
livro l[] = new livro[200];
Arrays.fill(l, new livro());
Here you are instantiating your array:
livro l[] = new livro[200];
However here you are attempting to access an element containing an object that does not exist yet:
l[i].cota = sc.nextLine();
You need to loop through and instantiate a new object at EVERY element. Either use a for loop or Array.fill.