Foro de elhacker.net

Programación => Java => Mensaje iniciado por: + 1 Oculto(s) en 11 Julio 2016, 02:27 am



Título: ejerciccio de competencia
Publicado por: + 1 Oculto(s) en 11 Julio 2016, 02:27 am
Código
  1. Is Bigger Smarter?
  2. Some people think that the bigger an elephant is, the smarter it is. To disprove this, you want to take
  3. the data on a collection of elephants and put as large a subset of this data as possible into a sequence
  4. so that the weights are increasing, but the IQ’s are decreasing.
  5. Input
  6. The input will consist of data for a bunch of elephants, one elephant per line, terminated by the endof-file.
  7. The data for a particular elephant will consist of a pair of integers: the first representing its size
  8. in kilograms and the second representing its IQ in hundredths of IQ points. Both integers are between
  9. 1 and 10000. The data will contain information for at most 1000 elephants. Two elephants may have
  10. the same weight, the same IQ, or even the same weight and IQ.
  11. Output
  12. Say that the numbers on the i-th data line are W[i] and S[i]. Your program should output a sequence
  13. of lines of data; the first line should contain a number n; the remaining n lines should each contain a
  14. single positive integer (each one representing an elephant). If these n integers are a[1], a[2],..., a[n] then
  15. it must be the case that
  16. W[a[1]] < W[a[2]] < ... < W[a[n]]
  17. and
  18. S[a[1]] > S[a[2]] > ... > S[a[n]]
  19. In order for the answer to be correct, n should be as large as possible. All inequalities are strict:
  20. weights must be strictly increasing, and IQs must be strictly decreasing.
  21. There may be many correct outputs for a given input, your program only needs to find one.
  22. Sample Input
  23. 6008 1300
  24. 6000 2100
  25. 500 2000
  26. 1000 4000
  27. 1100 3000
  28. 6000 2000
  29. 8000 1400
  30. 6000 1200
  31. 2000 1900
  32. Sample Output
  33. 4
  34. 4
  35. 5
  36. 9
  37. 7
  38.  
  39.  

alguna solucion ?? no se como comenzar  gracias y saludos



no logro entender como obtiener el Output, en realidad no entiendo el enunciado del todo


Título: Re: ejerciccio de competencia
Publicado por: AlbertoBSD en 11 Julio 2016, 15:16 pm
Hola

Del conjunto dado debes encontrar los n elementos qud cumplan la condicion

Citar
W[a[1]] < W[a[2]] < ... < W[a[n]]
and
S[a[1]] > S[a[2]] > ... > S[a[n]]

Entonces de la salida tenemos que:

Código
  1. 4 // Numero n de lineas siguientes
  2. 4 // datos 1000 4000
  3. 5 // datos 1100 3000
  4. 9 // datos 2000 1900
  5. 7 // datos 8000 1400
  6.  


Si te fijas la primera columna de los datos comentados va de menor a mayor y la segunda va de mayor a menor.

el n debe de ser el mas alto posible y pueden existir varios resultados por ejemplo en el ejercicio anterior el ultimo 7 también pudo ser 8

Código
  1. 8 //datos 6000 1200

Y conserva la mismas condiciones.

Como llegar al resultado deja pienso en un algoritmo.

Saludos



Ya vi es un problema de busqueda y ordenamiento estaba pensando varias formas de hacerlo y las mas eficientes son usando arboles y subarboles para evaluar coincidencias en subconjuntos


Título: Re: ejerciccio de competencia
Publicado por: + 1 Oculto(s) en 12 Julio 2016, 00:10 am
gracias por ayudarme, como obtener el n?


Título: Re: ejerciccio de competencia
Publicado por: AlbertoBSD en 12 Julio 2016, 00:58 am
Ese mi estimado es el detalle del algoritmo, hay que permutar de manera eficiente todas las combinaciones que cumplan esas restricciones y dar caulquiera de los resultados N.

Hay que usar lo mas eficiente ya que te indican que la máxima cantidad de inputs es de 1000.

Saludos


Título: Re: ejerciccio de competencia
Publicado por: + 1 Oculto(s) en 12 Julio 2016, 03:02 am
Código
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.ArrayList;
  5. import java.util.Collections;
  6. import java.util.Scanner;
  7. import java.util.StringTokenizer;
  8.  
  9.  
  10. public class Main {
  11.  
  12.    Elefantes maxEPHeader = null;
  13.  
  14.    static class Elefantes implements Comparable<Elefantes> {
  15.  
  16.        int peso = 0;
  17.        int iq = 0;
  18.        int n = 0;
  19.  
  20.        Elefantes(int p, int iq, int m) {
  21.            this.peso = p;
  22.            this.iq = iq;
  23.            this.n = m;
  24.        }
  25.  
  26.        @Override
  27.        public int compareTo(Elefantes o) {
  28.            if (this.peso > o.peso) {
  29.                return 1;
  30.            } else if (this.peso < o.peso) {
  31.                return -1;
  32.            } else if (this.iq < o.iq) {
  33.                return 1;
  34.            } else if (this.iq > o.iq) {
  35.                return -1;
  36.            }
  37.            return 0;
  38.        }
  39.    }
  40.  
  41.    public ArrayList<Elefantes> maxSecuencia(){
  42.  
  43.    return null;
  44.    }
  45.  
  46.    public static void main(String[] args) throws IOException {
  47.        ArrayList<Elefantes> e = new ArrayList<Elefantes>();
  48.        int inputCount = 1;
  49.        Main m = new Main();
  50.        String line;
  51.        StringTokenizer stk;
  52.        BufferedReader  scanner = new BufferedReader(new InputStreamReader(System.in));
  53.        while ((line=scanner.readLine())!=null) {
  54.            stk=new StringTokenizer(line," ");
  55.            Elefantes ele = new Elefantes(Integer.parseInt(stk.nextToken()), Integer.parseInt(stk.nextToken()), inputCount);
  56.            e.add(ele);
  57.            inputCount++;
  58.        }
  59.        Collections.sort(e);
  60.        System.out.println("jooooo      "+e);
  61.        scanner.close();
  62.    }
  63.  
  64. }
  65.  


no sale del ciclo while, no entiendo porque


Título: Re: ejerciccio de competencia
Publicado por: AlbertoBSD en 12 Julio 2016, 13:24 pm
Estas leyendo de system.in

En system.in nunca alcanza el fin  del archivo.

Cuando deberia de ser desde un archivo
Código
  1.   = new BufferedReader(new FileReader("foo.in"));

Saludos


Título: Re: ejerciccio de competencia
Publicado por: + 1 Oculto(s) en 12 Julio 2016, 18:22 pm
estoy pasando datos desde consola, se hace lo mismo con Scanner


saludos


Título: Re: ejerciccio de competencia
Publicado por: AlbertoBSD en 12 Julio 2016, 19:20 pm
Entonces necesitas tener una condicion de parada por ejemplo que cuando lea 0 0 se pare y no agrege esos valores.

Estos concursos siempre se hacen desde archivo y es mejor que lo hagas asi con el pero de los casos, si el ejemplo te dice que van a llegar 1000 datos, tu construye tu archivo con esos datos.

De hecho para este ejemplo en especifico hice este codigo para generar los numeros dichos:

Código
  1. #include<stdio.h>
  2. #include<time.h>
  3. #include<stdlib.h>
  4.  
  5. int main() {
  6. int i = 0;
  7. int aux1,aux2;
  8. srand(time(NULL));
  9. while(i < 1000) {
  10. aux1 = rand() % 10000;
  11. aux2 = rand() % 10000;
  12. printf("%i %i\n",aux1,aux2);
  13. i++;
  14. }
  15. return 0;
  16. }

Esta en C claro, pero lo compilo y redirijo la salida a un archivo .txt con el operador > de la consola.

Saludos!


Título: Re: ejerciccio de competencia
Publicado por: + 1 Oculto(s) en 13 Julio 2016, 15:01 pm
hice lo mismo en mis otros ejercicios y funcionaba

pero ahora no sale del while


Título: Re: ejerciccio de competencia
Publicado por: + 1 Oculto(s) en 18 Julio 2016, 06:42 am
este es mi codigo pero aun no funciona del todo


Código:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class Main {

    Elefantes maxEPHeader = null;

    static class Elefantes {

        int peso = 0;
        int iq = 0;
        int n = 0;

        Elefantes(int p, int iq, int m) {
            this.peso = p;
            this.iq = iq;
            this.n = m;
        }

    }

    public ArrayList<Elefantes> ordenar(ArrayList<Elefantes> listaElefantes) {
        for (int i = 0; i < listaElefantes.size(); i++) {
            for (int j = 0; j < listaElefantes.size() - i - 1; j++) {
                if (listaElefantes.get(j + 1).peso < listaElefantes.get(j).peso) {
                    Elefantes ele = listaElefantes.get(j + 1);
                    listaElefantes.set(j + 1, listaElefantes.get(j));
                    listaElefantes.set(j, ele);
                } else if (listaElefantes.get(j + 1).peso == listaElefantes.get(j).peso) {
                    if (listaElefantes.get(j + 1).iq < listaElefantes.get(j).iq) {
                        Elefantes ele = listaElefantes.get(j + 1);
                        listaElefantes.set(j + 1, listaElefantes.get(j));
                        listaElefantes.set(j, ele);
                    }
                }
            }
        }
        return listaElefantes;
    }

    public void clasificar(ArrayList<Elefantes> lista) {
        lista = ordenar(lista);
        int flag=1;
        for (int i = 0; i < lista.size(); i++) {
            System.out.println(lista.get(i).peso + " " + lista.get(i).iq + " " + lista.get(i).n);
        }
        Elefantes pivote = lista.remove(0);
        for (int i = 0; i < lista.size() - 1; i++) {
            if (lista.get(i).peso < lista.get(i + 1).peso) {
               
                if (lista.get(i).iq > lista.get(i + 1).iq) {
                    System.out.println(lista.get(i).n); 
                   
                }       
            }
           
        }

    }

    public static void main(String[] args) throws IOException {
        ArrayList<Elefantes> e = new ArrayList<>();
        int inputCount = 1;
        Main m = new Main();
        String line;
        StringTokenizer stk;
        BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
        while (!(line = scanner.readLine()).equals("")) {
            stk = new StringTokenizer(line, " ");
            Elefantes ele = new Elefantes(Integer.parseInt(stk.nextToken()), Integer.parseInt(stk.nextToken()), inputCount);
            e.add(ele);
            inputCount++;

        }

        m.clasificar(e);
        scanner.close();
    }

}