Exemple #1
0
 public static void main(String[] args) throws java.lang.Exception {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   Tree tree = new Tree();
   int n = Integer.parseInt(br.readLine());
   int nn = n - 1;
   TreeNode[] treeNodes = new TreeNode[n];
   int i = 0;
   while (n-- > 0) {
     String[] strs = br.readLine().split(" ");
     int r = Integer.parseInt(strs[1]);
     int n1 = Integer.parseInt(strs[0]);
     treeNodes[i] = new TreeNode(n1, r);
     i = i + 1;
   }
   boolean[] x = new boolean[nn + 1];
   while (nn-- > 0) {
     String[] strs = br.readLine().split(" ");
     int s = Integer.parseInt(strs[0]);
     int t = Integer.parseInt(strs[1]);
     if (!x[s]) {
       tree.insert(treeNodes[s]);
       x[s] = true;
     }
     if (!x[t]) {
       tree.insert(treeNodes[t]);
       x[t] = true;
     }
   }
   tree.levelOrder(tree.root);
 }
  public static void main(String[] args) throws Exception {

    /*  BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
    */
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 2000);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 2000);
    String[] s = br.readLine().split(" ");
    int n = Integer.parseInt(s[0]);
    int q = Integer.parseInt(s[1]);
    int num[] = new int[n + 1];
    int[] m = new int[3 * n + 1]; // size = 2*n+1
    Arrays.fill(num, -1);
    s = br.readLine().split(" ");
    for (int i = 1; i <= n; i++) num[i] = Integer.parseInt(s[i - 1]);
    /// build tree
    maketree(1, 1, n, m, num);

    for (int qq = 1; qq <= q; qq++) {
      s = br.readLine().split(" ");
      int i = Integer.parseInt(s[0]);
      int j = Integer.parseInt(s[1]);
      int ans = query(1, 1, n, m, num, i, j);
      out.write("" + num[ans] + "\n");
      out.flush();
    }
  }
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
  public static void findTextWord2(String wordToFind, String filePath) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
    boolean foundIt = false;
    int i = 1;
    String[] wordToFindarray = wordToFind.split(" ");

    for (String line = br.readLine(); line != null; line = br.readLine()) {
      String[] wordarray = line.split(" ");

      for (int j = 0; j < wordarray.length; j++) {
        for (int x = 0; x < wordToFindarray.length; x++) {
          if (wordToFindarray[x].equals(wordarray[j])) {
            System.out.println("Egyezes a(z)" + i + ". sor, " + (j + 1) + ". szavaval");
            foundIt = true;
            System.out.println(wordarray[j]);
          }
        }
      }
      i++;
    }
    if (!foundIt) {

      System.out.println("Nincs ilyen szo");
    }
  }
  public void findText(String wordToFind, String filePath, boolean caseSensitive)
      throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
    this.foundIt = false;
    this.i = 1;
    String[] wordToFindarray = wordToFind.split(" ");
    for (String line = br.readLine(); line != null; line = br.readLine()) {
      String[] wordarray = line.split(" ");
      if (wordToFindarray.length <= wordarray.length) {
        this.j = 0;
        while (wordToFindarray.length <= (wordarray.length - j)) {
          this.foundInside = true;
          this.plusCount = 1;
          if (caseSensitive) {
            this.findTextCS(wordToFindarray, wordarray);
          } else {
            this.findTextNCS(wordToFindarray, wordarray);
          }
          if (this.foundInside == true) {
            this.foundIt = true;
            System.out.println("Egyezes a(z)" + i + ". sor, " + (j + 1) + ". szavatol");
          }
          this.j++;
        }
      }
      this.i++;
    }
    if (!this.foundIt) {
      System.out.println("Nincs ilyen szo");
    }
  }
Exemple #6
0
  public static void main(String[] args) throws IOException {

    Scanner scanner = new Scanner(new BufferedInputStream(System.in));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
      int a = Integer.parseInt(br.readLine());
      if (a == 0) break;
      HashMap<String, Integer> map = new HashMap<String, Integer>();
      int sum = 0;

      while (a-- > 0) {
        StringTokenizer st = new StringTokenizer(br.readLine());
        int one = Integer.parseInt(st.nextToken()), two = Integer.parseInt(st.nextToken());
        country c = new country(one, two);
        country c_rev = new country(two, one);
        int s = 0;

        if (map.get(c.tostring()) != null) {
          s = map.get(c.tostring()) + 1;
          map.put(c.tostring(), s);
          sum++;
        } else if (map.get(c_rev.tostring()) != null) {
          s = map.get(c_rev.tostring()) - 1;
          map.put(c_rev.tostring(), s);
          sum--;
        } else {
          map.put(c.tostring(), 1);
          sum++;
        }
      }
      if (sum != 0) System.out.println("NO");
      else System.out.println("YES");
    }
  }
  public static void main(String[] args) throws Exception {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

    // byte digit[]=new byte[101];
    // boolean[] check=new boolean[101];
    // int num[]=new int[99999];
    ans = 0;
    int tests = Integer.parseInt(br.readLine());
    BigInteger f[] = new BigInteger[101];

    for (int i = 1; i <= 100; i++) {
      f[i] = new BigInteger(("" + i));
    }
    for (int i = 2; i <= 100; i++) {
      f[i] = f[i].multiply(f[i - 1]);
    }

    for (int i = 0; i < tests; i++) {

      int n = Integer.parseInt(br.readLine());
      out.write("\n" + f[n].toString());
      out.flush();
    }
  }
  public static void printFile(String filePath) throws IOException {

    File file = new File(filePath);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    for (String line = br.readLine(); line != null; line = br.readLine()) {
      System.out.println(line);
    }
  }
Exemple #9
0
  public static void main(String[] args) throws IOException {
    int num = 0;
    int guess = -1;
    int answer;
    String name;
    String line;
    String result;
    String scorefile = "highscores_java";

    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("guess.java - Guess a number between 1 and 100\n");

    // generate random number
    java.util.Random generator = new java.util.Random(System.currentTimeMillis());
    answer = generator.nextInt() / 42949673 + 50;

    // play game
    while (guess != answer) {
      num++;
      System.out.print("Enter guess " + num + ": ");
      result = stdin.readLine();
      guess = Integer.parseInt(result);
      if (guess < answer) {
        System.out.println("Higher...");
      } else if (guess > answer) {
        System.out.println("Lower...");
      }
    }
    System.out.println("Correct! That took " + num + " guesses.\n");

    // save high score
    System.out.print("Please enter your name: ");
    name = stdin.readLine();
    try {
      BufferedWriter outfile = new BufferedWriter(new FileWriter(scorefile, true));
      outfile.write(name + " " + num + "\n");
      outfile.close();
    } catch (IOException exception) {
      System.out.println("ERROR: Can't read from " + scorefile + "\n");
    }

    // print high scores
    try {
      BufferedReader infile = new BufferedReader(new FileReader(scorefile));
      while ((line = infile.readLine()) != null) {
        System.out.println(line);
      }
      infile.close();
    } catch (IOException exception) {
      System.out.println("ERROR: Can't read from " + scorefile + "\n");
    }
  }
Exemple #10
0
  public static void main(String[] args) throws java.lang.Exception {
    BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the first array of N elements(separator is 'space'): ");
    int a[] = toIntArray(buffer.readLine());
    System.out.println("Enter the second array of N elements(separator is 'space'): ");
    int[] b = toIntArray(buffer.readLine());
    // int [] a = {1,2,3,4};
    // int [] b = {1,4,5,6};

    ArrayList<Integer> c = merge(a, b);
    System.out.println("Median is: " + findMedian(c));
  }
Exemple #11
0
  public Main() {
    try {
      BufferedReader in;
      in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC
      int numLights = Integer.parseInt(in.readLine());
      int[] states = new int[numLights];
      for (int i = 0; i < numLights; i++) {
        states[i] = Integer.parseInt(in.readLine());
      }
      ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>();
      HashMap<String, Integer> dp = new HashMap<String, Integer>();

      int moves = 0;
      Q.addLast(new Scenario(states));
      while (!Q.isEmpty()) {
        int size = Q.size();
        for (int q = 0; q < size; q++) {
          Scenario temp = Q.removeFirst();
          if (isEmpty(temp.states)) {
            System.out.println(moves);
            return;
          } else {
            for (int i = 0; i < temp.states.length; i++) {
              if (temp.states[i] == 0) {
                int[] newArr = Arrays.copyOf(temp.states, temp.states.length);
                newArr[i] = 1;
                newArr = fixArray(newArr);
                String arr = "";
                for (int p = 0; p < newArr.length; p++) arr += newArr[p];
                if (dp.get(arr) == null) {
                  dp.put(arr, moves);
                  Q.addLast(new Scenario(newArr));
                } else {
                  int val = dp.get(arr);
                  if (val != 0 && moves < val) {
                    dp.put(arr, moves);
                    Q.addLast(new Scenario(newArr));
                  }
                }

                // outputArr(newArr);
              }
            }
          }
        }
        moves++;
      }

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }
  /* sets the parts of speech for each node in the graph */
  public void addPOS() {
    System.out.println("Running POS tagger...");
    /* parameters for exec command */
    File dir = new File("/home/josh/Desktop/Artificial_Intelligence/POS_Tagger");
    /* where we are placing the file to parse */
    File result = new File(file.toString() + ".pos");
    int i = 1;
    String s = null, data = "";
    try {
      /* command to run the POS tagger */
      String command =
          "java -mx300m -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTagger -model models/"
              + "bidirectional-distsim-wsj-0-18.tagger -textFile "
              + file.toString();

      /* run the process */
      Process p = Runtime.getRuntime().exec(command, null, dir);
      i = p.waitFor();

      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

      /* extract the data from the command */

      while ((s = stdInput.readLine()) != null) {
        /* copy the data into one string */
        data += s;
      }
      /* place the data in a .pos text file */
      byte[] buffer = data.getBytes();
      FileOutputStream fout = new FileOutputStream(result, false);
      fout.write(buffer);
      fout.close();

      /* read any errors from the attempted command */
      while ((s = stdError.readLine()) != null) {
        System.out.println(s);
      }

    } catch (Exception e) {
      System.out.println("Exception happened - here's what I know: ");
      e.printStackTrace();
      System.exit(-1);
    }
    /* wait for the above process to complete */
    while (i == 1) ;
    /* update our file to include the POS tags */
    this.file = result;
  }
  public static void findTExtLetters(String letterToFind, String filePath) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
    boolean foundIt = false;
    int i = 1;
    String[] letterToFindarray = letterToFind.split("");

    for (String line = br.readLine(); line != null; line = br.readLine()) {

      String[] letterarray = line.split("");

      for (int j = 0; j < letterarray.length; j++) {
        for (int x = 0; x < letterToFindarray.length; x++) {
          if (letterToFindarray[x].equals(letterarray[j])) {
            System.out.println("Egyezes a(z)" + i + ". sor, " + (j + 1) + ". karakterrel");
            foundIt = true;
          } else {
            char m = letterToFindarray[x].charAt(0);
            int o = (int) m;
            if (o < 95) { // nagy betűt keresek és kis betű a keresendőben
              char n = letterarray[j].charAt(0);
              int p = (int) n;
              p = p - 32;
              n = (char) p;
              String backToString = Character.toString(n);
              if (letterToFindarray[x].equals(backToString)) {
                System.out.println("Egyezes a(z)" + i + ". sor, " + (j + 1) + ". karakterrel");
                foundIt = true;
              }
            } else { //// kis betűt keresek és nagy betű a keresendőben
              char n = letterarray[j].charAt(0);
              int p = (int) n;
              p = p + 32;
              n = (char) p;
              String backToString = Character.toString(n);
              if (letterToFindarray[x].equals(backToString)) {
                System.out.println("Egyezes a(z)" + i + ". sor, " + (j + 1) + ". karakterrel");
                foundIt = true;
              }
            }
          }
        }
      }
      i++;
    }
    if (!foundIt) {
      System.out.println("Nincs ilyen szo");
    }
  }
Exemple #14
0
  public void scanSolution(String path) {
    String line = null;
    try {

      File filescan = new File("res/" + path);

      // System.out.println("res/"+path);
      FileReader f = new FileReader(filescan);

      BufferedReader fileReader = new BufferedReader(f);

      while ((line = fileReader.readLine()) != null) {
        String[] data = line.split(" ");

        // System.out.println(data[0]);

        if (data[0].equals("PAINT_LINE")) {

          paint_line(
              Integer.parseInt(data[1]),
              Integer.parseInt(data[2]),
              Integer.parseInt(data[3]),
              Integer.parseInt(data[4]));
        } else { // implement other methods...
        }
      }

    } catch (FileNotFoundException e) {
      System.out.println("Error opening file!");
    } catch (IOException ex) {
      System.out.println("Error reading file!!!!");
    }
  }
Exemple #15
0
 // =========================================================
 public String recieve() throws IOException // RECIEVE METHOD
     {
   String recievedString;
   recievedString = buffRdr.readLine();
   System.out.println("RECD<<<< " + id + ": " + recievedString);
   return recievedString;
 }
Exemple #16
0
  public static void search(int[] weights, BufferedReader in, int boundary) throws IOException {
    if (boundary == weights.length) return;
    else {
      final int TEMP = boundary + 1;
      int[] tmp = new int[TEMP];

      String line = in.readLine();
      StringTokenizer tokenizer = new StringTokenizer(line);
      for (int i = 0; i < TEMP; ++i) tmp[i] = Integer.parseInt(tokenizer.nextToken());

      int adding = weights[0];
      for (int i = 0; i < TEMP; ++i) {
        if (i == 0 || i == (TEMP - 1)) weights[i] = adding + tmp[i];
        else {
          int temp1 = adding + tmp[i];
          adding = weights[i];
          int temp2 = adding + tmp[i];
          if (temp1 > temp2) weights[i] = temp1;
          else weights[i] = temp2;
        }
      }
    }
    search(weights, in, boundary + 1);
    return;
  }
  public static void findTextWord(String wordToFind, String filePath) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
    boolean foundIt = false;
    int i = 1;
    String[] wordToFindarray = wordToFind.split(" ");

    for (String line = br.readLine(); line != null; line = br.readLine()) {
      String[] wordarray = line.split(" ");
      if (wordToFindarray.length > wordarray.length) {

      } else {
        int j = 0;
        while (wordToFindarray.length < (wordarray.length - j + 1)) {

          boolean foundinside = true;
          int pluscount = 1;
          if (wordToFindarray[0].equals(wordarray[j])) {
            if (wordToFindarray.length < 2) {
              System.out.println("Egyezes a(z)" + i + ". sor, " + (j + 1) + ". szavatol");
              foundIt = true;
            } else {
              do {
                if (wordToFindarray[pluscount].equals(wordarray[j + pluscount])) {
                  pluscount++;
                } else {
                  foundinside = false;
                }
              } while ((pluscount < (wordToFindarray.length)) && (foundinside == true));
            }
          } else {
            foundinside = false;
          }
          if (foundinside == true) {
            foundIt = true;
          }
          j++;
        }
      }

      i++;
    }
    if (!foundIt) {

      System.out.println("Nincs ilyen szo");
    }
  }
  void run() throws Exception {
    // for this PS3, you can alter this method as you see fit

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    int TC = Integer.parseInt(br.readLine()); // there will be several test cases
    while (TC-- > 0) {
      br.readLine(); // ignore dummy blank line
      V = Integer.parseInt(br.readLine());

      StringTokenizer st = new StringTokenizer(br.readLine());
      // read rating scores, A (index 0), B (index 1), C (index 2), ..., until the V-th index
      RatingScore = new int[V];
      for (int i = 0; i < V; i++) {
        RatingScore[i] = Integer.parseInt(st.nextToken());
      }

      // clear the graph and read in a new graph as Adjacency Matrix
      AdjMatrix = new TreeMap<Integer, TreeMap<Integer, Boolean>>();
      for (int i = 0; i < V; i++) {
        st = new StringTokenizer(br.readLine());
        int k = Integer.parseInt(st.nextToken());

        TreeMap<Integer, Boolean> g = AdjMatrix.get(i);
        if (g == null) {
          g = new TreeMap<Integer, Boolean>();
          AdjMatrix.put(i, g);
        }

        while (k-- > 0) {
          int j = Integer.parseInt(st.nextToken());

          g.put(j, true);
          TreeMap<Integer, Boolean> gCon = AdjMatrix.get(j);
          if (gCon == null) {
            gCon = new TreeMap<Integer, Boolean>();
            AdjMatrix.put(j, gCon);
          }

          gCon.put(i, true);
        }
      }

      pr.println(Query());
    }
    pr.close();
  }
Exemple #19
0
  public static void main(String[] args) throws IOException {

    String input;
    System.out.print("Please enter a word... ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    input = in.readLine();
    print(input);
  }
  public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    String[] split = null;

    int cases = Integer.valueOf(reader.readLine());
    int N, j, z, min, max, result;

    String matching = null, newMatch = null, tmpLine;
    Set<String> set = new HashSet<String>();
    boolean noResult = false;

    for (int i = 1; i <= cases; i++) {
      N = Integer.valueOf(reader.readLine());
      set = new HashSet<String>();
      noResult = false;
      result = 0;
      min = Integer.MAX_VALUE;
      max = Integer.MIN_VALUE;

      for (z = 0; z < N; z++) {
        line = reader.readLine();
        tmpLine = REGEX_PATTERN.matcher(line).replaceAll("$1");

        if (set.isEmpty()) {
          set.add(tmpLine);
        } else if (!set.contains(tmpLine)) {
          noResult = true;
          break;
        }

        min = Math.min(min, line.length());
        max = Math.max(max, line.length());
      }

      if (!noResult) {
        result = max - min;
      }

      if (noResult) {
        System.out.printf("Case #%d: Fegla Won%n", i);
      } else {
        System.out.printf("Case #%d: %d%n", i, result);
      }
    }
  }
Exemple #21
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader("numtri.in"));
    PrintWriter out = new PrintWriter(new FileWriter("numtri.out"));

    int r = Integer.parseInt(in.readLine());
    final int LEN = r;
    int[] weights = new int[LEN];

    weights[0] = Integer.parseInt(in.readLine());

    search(weights, in, 1);
    insertionSort(weights, r);

    out.println(weights[r - 1]);
    in.close();
    out.close();
    System.exit(0);
  }
Exemple #22
0
 protected String readline() throws IOException {
   String s = in.readLine();
   if (DEBUG) dbg("FROM TT: <" + s + ">");
   if (s.startsWith("error:")) {
     dbg("ThoughtTreasure " + s);
     return "";
   }
   return s;
 }
  // You shouldn't modify this function
  // This function gets an update from the server each time your car reaches a new node
  // The server supplies you with the following information:
  //      1. Reward/cost information: travelCost: the cost (measured in happiness units) you
  // incurred for traveling over the last link
  //                               payout: the number of happiness units you got for arriving at the
  // current node
  //                               tollCharge: the amount of toll charge you incurred for traveling
  // the latest link
  //      2. currentNode: the current node position your car is at in the world (value between 0-3)
  //      3. currentUtilitiesforVisitingNode [array of 4]: The number of happiness units you will
  // get in the future for arriving at each of the 4 nodes
  public boolean readStatusMessage() {
    try {
      //            System.out.println(sin.readLine());
      String[] buf = sin.readLine().split(" ");

      if (buf[0].equals("quit")) return false;

      travelCost = Double.valueOf(buf[1]);
      payout = Double.valueOf(buf[2]);
      tollCharge = Double.valueOf(buf[3]);
      System.out.println("Results: " + travelCost + " " + payout + " " + tollCharge);

      // parse my current position in the world
      String[] buf2 = sin.readLine().split(" ");
      currentNode = Integer.valueOf(buf2[1]);
      System.out.println("Position: " + currentNode);

      // parse my utilities for visiting each node
      String[] buf3 = sin.readLine().split(" ");
      int i;
      for (i = 0; i < numNodes; i++)
        currentUtilitiesforVisitingNodes[i] = Double.valueOf(buf3[i + 1]);
      System.out.println(
          "Utilities: "
              + currentUtilitiesforVisitingNodes[0]
              + " "
              + currentUtilitiesforVisitingNodes[1]
              + " "
              + currentUtilitiesforVisitingNodes[2]
              + " "
              + currentUtilitiesforVisitingNodes[3]);

      // parse linkState stuff
      String[] buf4 = sin.readLine().split(" ");
      aveOnLink = Double.valueOf(buf4[1]);
      capacity = Integer.parseInt(buf4[2]);
      System.out.println("linkState: " + aveOnLink + " " + capacity);
    } catch (IOException e) {
      System.out.println(e);
      return false;
    }

    return true;
  }
Exemple #24
0
  public void line_reader(String file) throws IOException, FileNotFoundException {

    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
      line = line.trim();
      line = line.replaceAll("\"([\\*]*)\"", "");
      tokenizer(line);
    }
  }
Exemple #25
0
 protected Vector /* of String */ readlines() throws IOException {
   Vector r = new Vector();
   while (true) {
     String s = in.readLine();
     if (DEBUG) dbg("FROM TT: <" + s + ">");
     if (s.equals(".")) break;
     if (s.startsWith("error:")) break;
     r.addElement(s);
   }
   return r;
 }
  public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    String[] splitLine = null;
    while ((line = reader.readLine()) != null) {
      if (line.isEmpty()) {
        System.out.println();
        continue;
      }

      int N = Integer.valueOf(line);
      int[] array = new int[N];
      splitLine = reader.readLine().split("\\s+");
      for (int i = 0; i < N; i++) {
        array[i] = Integer.valueOf(splitLine[i]);
      }
      int M = Integer.valueOf(reader.readLine());

      Arrays.sort(array);

      int minDifference = Integer.MAX_VALUE;
      int i = 0, j = 0;

      for (int a = 0; a < N; a++) {
        int first = array[a];
        int b = binary_search(array, M - first, 0, N - 1, a);
        if (b >= 0) {
          int second = array[b];
          if ((first + second) == M) {
            if (minDifference > Math.abs(first - second)) {
              j = second;
              i = first;
              minDifference = Math.abs(first - second);
            }
          }
        }
      }

      System.out.println("Peter should buy books whose prices are " + i + " and " + j + ".");
    }
  }
  public static void findTextLine(String lineToFind, String filePath) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
    boolean foundIt = false;
    int i = 1;
    String[] lineToFindarray = lineToFind.split(" ");
    for (String line = br.readLine(); line != null; line = br.readLine()) {
      for (int x = 0; x < lineToFindarray.length; x++) {
        if (lineToFindarray[x].equals(line)) {
          System.out.println("Talalat a(z)" + i + ". sorban!");
          foundIt = true;
          System.out.println(line);
        }
      }
      i++;
    }
    if (!foundIt) {

      System.out.println("Nincs ilyen sor");
    }
  }
Exemple #28
0
 public Mouvement jouer() {
   // System.out.println("Liste des coups possibles : ");
   /*
   for(Mouvement[] coupsPossibles : coupPossible)
   	System.out.println("1ere:"+coupPossible.getPremiere()+" 2e:"+coupPossible.getDerniere()+" vecteur:"+coupPossible.getVecteur());
   */
   try {
     System.out.print("Premiere bille : ");
     byte premiere = new Byte(br.readLine());
     System.out.print("Seconde bille : ");
     byte seconde = new Byte(br.readLine());
     System.out.print("Vecteur : ");
     byte vecteur = new Byte(br.readLine());
     System.out.println("mouvement choisi : ");
     coupChoisi = new Mouvement(premiere, seconde, vecteur);
     return coupChoisi;
   } catch (IOException e) {
     System.err.println("Joueur::jouer() -> erreur de lecture du mouvement a la ligne de cmd.");
   }
   return new Mouvement((byte) 1, (byte) 1, (byte) 1);
 }
Exemple #29
0
 /**
  * Reads the population from a file.
  *
  * @param fileName is the file name where the classifiers have to be read.
  */
 public void readPopulationFromFile(String fileName) {
   String line = null;
   try {
     System.out.print("\n LOADING POPULATION FROM FILE");
     BufferedReader fin = new BufferedReader(new FileReader(fileName));
     macroClSum =
         new Integer(fin.readLine().trim())
             .intValue(); // We write the number of macro classifiers.
     microClSum =
         new Integer(fin.readLine().trim())
             .intValue(); // We write the number of micro classifiers.
     fin.readLine(); // This line is only information to interpret the file.
     for (int i = 0; i < macroClSum; i++) {
       line = fin.readLine();
       set[i] = new Classifier(new StringTokenizer(line));
     }
     fin.close();
     System.out.println(": done!");
   } catch (IOException eio) {
     System.out.println(
         "ERROR when reading the population from the file: " + fileName + ": " + eio);
   }
 } // end readPopulationFromFile
Exemple #30
0
 public static void main(String[] args) throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("treasure.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("treasure.out")));
   StringTokenizer st = new StringTokenizer(f.readLine());
   int N = Integer.parseInt(st.nextToken());
   int[] coins = new int[N];
   for (int i = 0; i < N; i++) {
     st = new StringTokenizer(f.readLine());
     coins[i] = Integer.parseInt(st.nextToken());
   }
   int min = 0;
   int max = N - 1;
   int ans = 0;
   int other = 0;
   int counter = 0;
   while (min < max) {
     if (coins[min] > coins[max]) {
       if (counter % 2 == 0) {
         ans += coins[min];
       } else {
         other += coins[min];
       }
       min++;
     } else {
       if (counter % 2 == 0) {
         ans += coins[max];
       } else {
         other += coins[max];
       }
       max--;
     }
     counter++;
   }
   out.println(ans);
   out.close();
   System.exit(0);
 }