Exemplo n.º 1
1
  public static void main(String[] args) throws IOException {
    in = new Reader();
    out = new PrintWriter(System.out, true);

    int N = in.nextInt();

    PriorityQueue<Long> pq = new PriorityQueue<Long>();
    for (int i = 0; i < N; i++) pq.add(in.nextLong());

    long cost = 0;
    while (pq.size() > 1) {
      long a = pq.poll() + pq.poll();
      cost += a;
      pq.add(a);
    }

    out.println(cost);
  }
Exemplo n.º 2
0
  /**
   * piirtää reitin tiedostoon ja reittikartta taulukkoon
   *
   * @param käydytsolmut
   * @throws IOException
   */
  public void piirräreitti(PriorityQueue<Solmu> käydytsolmut) throws IOException {

    String nimi = new String("uk");
    BufferedWriter reittikarttatiedosto = new BufferedWriter(new FileWriter("uk"));
    Solmu solmu = new Solmu(0, 0, null, 0);

    while (!käydytsolmut.isEmpty()) {
      solmu = käydytsolmut.poll();

      for (int n = 0; n < kartankoko; n++) {
        for (int i = 0; i < kartankoko; i++) {
          if (solmu.x == n && solmu.y == i) {
            // reittikartta[i][n] = '-';
            reittikartta[i][n] = (char) (solmu.summaamatkat(0, solmu.annavanhempi()) + 65);
            // reittikarttatiedosto.write("-");
            reittikarttatiedosto.write('-');
          } else {
            reittikarttatiedosto.write(reittikartta[i][n]);
          }
        }
        reittikarttatiedosto.newLine();
      }
    }
    reittikarttatiedosto.close();
    tulostakartta(reittikartta);
  }
Exemplo n.º 3
0
  private static PencilPosition findShortestRoute(int[][] maze) {
    // all found solutions to the maze
    PriorityQueue<PencilPosition> solutions =
        new PriorityQueue<PencilPosition>(5, new PencilPositionComparator());
    // bread-first search queue
    Queue<PencilPosition> routes = new LinkedList<PencilPosition>();
    // set of already visited positions
    Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>();

    // add the starting positions, which is always (0,0)
    routes.add(new PencilPosition(0, 0, false, null));

    while (!routes.isEmpty()) {
      PencilPosition position = routes.poll();

      // if this is the destinations position then we've found a solution
      if (0 == maze[position.row][position.column]) {
        solutions.add(position);
        continue;
      }

      // if we haven't already visited this position
      if (!visitedPositions.contains(position)) {
        routes.addAll(findPossibleRoutes(position, maze));
        visitedPositions.add(position);
      }
    }

    return solutions.poll();
  }
  public static void solveOne() throws Exception {
    int n = nextInt();
    int m = nextInt();
    int k = nextInt();
    int w = nextInt();
    char[][][] levels = new char[k][n][];
    ;
    for (int i = 0; i < k; i++) {
      for (int j = 0; j < n; j++) {
        levels[i][j] = nextString().toCharArray();
      }
    }
    int[][] cost = new int[k][k];
    PriorityQueue<int[]> q =
        new PriorityQueue<>(
            k * k,
            new Comparator<int[]>() {
              @Override
              public int compare(int[] o1, int[] o2) {
                return o1[2] - o2[2];
              }
            });
    for (int i = 0; i < k; i++) {
      for (int j = i + 1; j < k; j++) {
        int[] cur = {i, j, diff(levels[i], levels[j]) * w};
        cost[i][j] = cur[2];
        q.add(cur);
        //              px("edge", cur);
      }
    }
    //      px(q.size());
    //      for (int[] e: cost) px(e);
    DisjointUnionSet djs = new DisjointUnionSet(k);
    boolean[][] al = new boolean[k][k];
    int finalCost = n * m * k;
    for (; q.size() > 0; ) {
      int[] edge = q.poll();
      int p1 = djs.getPartitionId(edge[0]);
      int p2 = djs.getPartitionId(edge[1]);
      //          px(edge, p1 == p2, edge[2]);
      if (edge[2] > n * m) break;
      if (p1 != p2) {

        djs.unionElement(edge[0], edge[1]);
        finalCost -= n * m - edge[2];
        al[edge[1]][edge[0]] = true;
        al[edge[0]][edge[1]] = true;
      }
    }
    //      for (boolean[] e: al) px(e);
    pn(finalCost);
    boolean[] ex = new boolean[k];
    for (int i = 0; i < k; i++) {
      if (!ex[i]) {
        dfs(i, -1, ex, k, al);
      }
    }
  }
Exemplo n.º 5
0
  public static void dijkstra_function(graph G, int s, int no)
      throws IOException { // s is the index of the starting vertex
    // declare variables
    int nVerts, u, v;
    int[] dist;

    nVerts = G.vertices(); // get number of vertices in the graph class

    // initialize array
    dist = new int[nVerts];
    Stack[] path = new Stack[nVerts];
    for (v = 0; v < nVerts; v++) // initializations
    {
      dist[v] = 99999; // 99999 represents infinity
      path[v] = new Stack<Integer>();
      path[v].push(s);
    } // end for

    dist[s] = 0;

    PriorityQueue Q = new PriorityQueue(dist);

    while (Q.Empty() == 0) // if heap is not empty
    {

      u = Q.Delete_root();
      v = G.nextneighbor(u);

      while (v != -1) // for each neighbor of u
      {
        if (dist[v] > dist[u] + G.edgeLength(u, v)) {
          dist[v] = dist[u] + G.edgeLength(u, v);
          path[v].pop();
          path[v].push(u);
          Q.Update(v, dist[v]);
        }

        v = G.nextneighbor(u); // get the next neighbor of u
      } // end while
    } // end while
    for (v = 0; v < nVerts; v++) // initializations
    {
      while ((Integer) path[v].peek() != s) {
        int top = (Integer) path[v].peek();
        for (int i = 0; i < path[top].size(); i++) {
          path[v].push(path[top].get(i));
        }
      }
    }
    FileWriter fw = new FileWriter("path" + no + ".txt");
    for (int i = 0; i < nVerts; i++) {
      fw.write(dist[i] + " ");
      while (!path[i].empty()) fw.write((Integer) path[i].pop() + " ");
      fw.write(i + "\n");
    } // end for
    fw.close();
  } // end bfs_function
 public static String next() {
   if (pq.peek() != null) {
     System.out.println("queue pop");
     String curUrl = pq.remove().url;
     if (!visitedUrl.contains(curUrl)) {
       visitedUrl.add(curUrl);
       return curUrl;
     } else return null;
   } else return null;
 }
  static void sweep(ArrayList<Integer> indexes) {
    PriorityQueue<Event> pq = new PriorityQueue<Event>();
    for (int i = 0; i < indexes.size(); i++) {
      pq.offer(new Event(lo[val[indexes.get(i)]] + 1, 1, indexes.get(i)));
      pq.offer(new Event(hi[val[indexes.get(i)]], -1, indexes.get(i)));
    }

    TreeSet<Integer> active = new TreeSet<Integer>();
    while (!pq.isEmpty()) {
      Event curr = pq.poll();
      if (curr.type == 1) active.add(curr.index);
      else if (curr.type == -1) {
        active.remove(curr.index);
        Integer lower = active.lower(curr.index);
        if (lower != null && lower > lo[val[curr.index]]) {
          Interval add = new Interval(lower, curr.index);
          Interval prev = intervals.floor(add);
          Interval next = intervals.ceiling(add);
          boolean intersectPrev = true;
          boolean intersectNext = true;

          if (prev != null) {
            if (Math.max(add.l, prev.l) < Math.min(add.r, prev.r)) {
              if (add.r - add.l <= prev.r - prev.l) {
                intervals.remove(prev);
                intersectPrev = false;
              }
            } else {
              intersectPrev = false;
            }
          } else {
            intersectPrev = false;
          }

          if (next != null) {
            if (Math.max(add.l, next.l) < Math.min(add.r, next.r)) {
              if (add.r - add.l <= next.r - next.l) {
                intervals.remove(next);
                intersectNext = false;
              }
            } else {
              intersectNext = false;
            }
          } else {
            intersectNext = false;
          }

          if (!intersectPrev && !intersectNext) intervals.add(add);
        }
      }
    }
  }
 // 保存待访问的URL及其优先级
 private static void SavePriorQueue(String filepath) throws Exception {
   BufferedWriter bw = new BufferedWriter(new FileWriter(filepath));
   PriorityQueue<UrlValue> temp = new PriorityQueue<UrlValue>();
   UrlValue cur = null;
   while (pq.peek() != null) {
     cur = pq.remove();
     temp.offer(cur);
     bw.write(cur.url + " " + cur.value);
     bw.newLine();
   }
   pq = temp;
   bw.flush();
   bw.close();
 }
Exemplo n.º 9
0
 /**
  * käy solmun vanhemmat ja pistää ne priorityqueue:n
  *
  * @param käydytsolmut
  * @param vikasolmu
  * @return
  */
 public PriorityQueue<Solmu> käysolmuttakaperin(
     PriorityQueue<Solmu> käydytsolmut, Solmu vikasolmu) {
   if (!vikasolmu.onkoalkusolmu) {
     käydytsolmut.add(vikasolmu);
     käysolmuttakaperin(käydytsolmut, vikasolmu.vanhempi);
   }
   return käydytsolmut;
 }
Exemplo n.º 10
0
  // experimental
  // ====================================================================
  // ====================================================================
  // ====================================================================
  private void readAndDrawBIGGraph(String file) {
    // behövs inte än
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); //
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        // this is a fix: fixa att Kålltorp och Torp är samma hållplats
        if (hpl.equals("Torp")) {
          xco += 11;
          hpl = "   / Torp";
        }
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      Color color =
          new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); //
      String lineNo = "1"; //
      while (indata.hasNext()) { // assume lines are correct
        int from = noderna.find(indata.next()).getNodeNo();
        int to = noderna.find(indata.next()).getNodeNo();
        grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
        indata.nextLine(); // skip rest of line
        // Draw
        BusStop busFrom = noderna.find(from);
        BusStop busTo = noderna.find(to);
        karta.drawLine(
            busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE);
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawBIGGraph
Exemplo n.º 11
0
  static void test00() {
    Aron.beg();
    PriorityQueue<Interval> queue = new PriorityQueue<Interval>();
    Stack<Interval> stack = new Stack<Interval>();
    int[] arr1 = {4, 1, 2, 6, 9};
    int[] arr2 = {5, 1, 4, 9, 10};

    for (int i = 0; i < arr1.length; i++) {
      queue.add(new Interval(arr1[i], arr2[i]));
    }
    if (queue.size() > 0) {
      stack.push(queue.remove());
    }
    while (!queue.isEmpty()) {
      Interval top = stack.peek();
      Interval inter = queue.remove();
      if (top.end < inter.begin) stack.push(inter);
      else {
        stack.peek().end = Math.max(stack.peek().end, inter.end);
      }
    }
    while (!stack.empty()) {
      System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]");
      stack.pop();
    }

    Aron.end();
  }
Exemplo n.º 12
0
  static void solve(Scanner sc) throws IOException {
    int h = sc.nextInt();
    int w = sc.nextInt();
    int k = sc.nextInt();
    PriorityQueue<Node> pq = new PriorityQueue<Node>();
    for (int i = 0; i < h; i++) {
      String s = sc.next();
      for (int j = 0; j < w; j++) {
        grid[i][j] = s.charAt(j);
        dis[i][j] = grid[i][j] == '#' ? 0 : inf;
        if (grid[i][j] == 'S') pq.offer(new Node(i, j, 0));
      }
    }

    // Dijkstra
    // There is always a solution according to problem statement
    while (!pq.isEmpty()) {
      Node z = pq.poll();
      int x = z.x;
      int y = z.y;
      int d = z.dis;
      if (d > dis[x][y]) continue;
      if (x == 0 || x == h - 1 || y == 0 || y == w - 1) {
        System.out.println(d + 1);
        break;
      }
      for (int i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        // if(nx<0||nx>=h||ny<0||ny>=w)
        //    continue;
        int nd = d + 1 + (grid[nx][ny] == '@' ? k : 0);
        if (nd < dis[nx][ny]) {
          dis[nx][ny] = nd;
          pq.offer(new Node(nx, ny, nd));
        }
      }
    }
  }
 // 清除所有优先队列的数据,设置优先种子
 private static void SetSeeds(String filepath) throws Exception {
   pq.clear();
   BufferedReader br = new BufferedReader(new FileReader(filepath));
   String line = null;
   UrlValue cur = null;
   visitedPrint();
   while ((line = br.readLine()) != null) {
     line = line.trim();
     // System.out.println(line);
     if (!line.equals("")) {
       if (!visitedUrl.contains(line)) {
         cur = new UrlValue();
         cur.url = line;
         cur.value = 1;
         pq.offer(cur);
       } else {
         System.out.println("contain");
       }
     }
   }
   br.close();
 }
Exemplo n.º 14
0
  @Override
  void solve(Set<? extends Job> jobs) {
    Job[] sortedJobs = jobs.toArray(new Job[jobs.size()]);
    Arrays.sort(sortedJobs, Job::compareArrivalTime);

    processTime = totWT = 0;
    long usefulTime = 0;
    int jobCount = jobs.size();
    PriorityQueue<Job> queue = new PriorityQueue<>(Job::compareBurstTime);
    for (Job job : sortedJobs) {
      if (job == null) {
        jobCount--;
        continue;
      }

      while (!queue.isEmpty() && processTime < job.getArrivalTime()) {
        Job nextJob = queue.poll();
        long arrivalTime = nextJob.getArrivalTime();
        long burstTime = nextJob.getBurstTime();

        if (processTime < nextJob.getArrivalTime()) {
          processList.add(new RunningProcess("Idle", arrivalTime - processTime));
          processTime = arrivalTime;
        }

        processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
        usefulTime += burstTime;
        totWT += processTime - arrivalTime;
        processTime += burstTime;
      }

      queue.add(job);
    }

    while (!queue.isEmpty()) {
      Job nextJob = queue.poll();
      long arrivalTime = nextJob.getArrivalTime();
      long burstTime = nextJob.getBurstTime();

      if (processTime < nextJob.getArrivalTime()) {
        processList.add(new RunningProcess("Idle", arrivalTime - processTime));
        processTime = arrivalTime;
      }

      processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
      usefulTime += burstTime;
      totWT += processTime - arrivalTime;
      processTime += burstTime;
    }

    totRT = totWT;
    totTAT = totWT + usefulTime;

    avgRT = avgWT = (double) totWT / (double) jobCount;
    avgTAT = (double) totTAT / (double) jobCount;

    utilization = usefulTime * 100.0 / processTime;
  }
Exemplo n.º 15
0
  private static int dijkstra(int s, int e, int[] cost, int[][] flow) {
    int[] best = new int[cost.length];
    Arrays.fill(best, -1);
    best[s] = cost[s];
    PriorityQueue<Node> pq = new PriorityQueue<Node>();
    pq.add(new Node(cost[s], s));
    while (pq.size() > 0) {
      Node n = pq.poll();

      if (n.at == e) return n.cost;
      if (n.cost < best[n.at]) continue;
      for (int i = 0; i < cost.length; i++) {
        if (flow[n.at][i] > 0) {
          int c = min(cost[i], n.cost);
          if (c > best[i]) {
            best[i] = c;
            pq.add(new Node(c, i));
          }
        }
      }
    }
    return 0;
  }
 void clear() {
   pending_entries.clear();
   output_set.clear();
   object_tasks.clear();
   active_threads.clear();
   time_marks.clear();
   thread_entries = null;
   next_time = 0;
   end_time = 0;
   current_thread = null;
   thread_map.clear();
   cpu_time = null;
   thread_counter = 0;
   task_counter = 0;
   max_delta = 1;
 }
Exemplo n.º 17
0
  public void getIndexInfo(String indexdir, int freqThreshold) {
    IndexReader reader = null;

    try {
      Directory dir = FSDirectory.open(new File(indexdir));
      System.out.println(dir);
      reader = IndexReader.open(dir);

      System.out.println("document num:" + reader.numDocs());
      System.out.println("======================");

      TermEnum terms = reader.terms();
      sortedTermQueue.clear();
      maxDocNum = reader.maxDoc();
      linkMap.clear();
      termList.clear();
      while (terms.next()) {
        // System.out.print(terms.term() + "\tDocFreq:" +
        TermDocs termDocs = reader.termDocs(terms.term());
        MyTerm temp = new MyTerm(terms.term(), termDocs, maxDocNum);
        if (temp.totalFreq < freqThreshold) {
          continue;
        } /*
           * if(temp.originTrem.text().length()==1){ continue; }
           */
        linkMap.put(temp.originTrem.text(), temp);
        sortedTermQueue.add(temp);
        termList.add(temp);
      }
      System.out.println("total Size:" + sortedTermQueue.size());
      System.out.println("mapsize:" + linkMap.keySet().size());
      // System.exit(0);
      int num = 0;
      this.maxFreq = sortedTermQueue.peek().totalFreq;
      while (!sortedTermQueue.isEmpty()) {
        num++;
        System.out.println(num + ":" + sortedTermQueue.poll());
      }
      System.out.println("read index info done");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        reader.close();

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  // 加载待访问的url
  private static void SetPriorQueue(String filePath) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(filePath));
    Scanner sc = null;
    String line = null;
    String url = null;
    UrlValue cur = null;

    while ((line = br.readLine()) != null) {
      line = line.trim();
      if (!line.equals("")) {
        sc = new Scanner(line);
        url = sc.next();
        if (!visitedUrl.contains(url)) {
          cur = new UrlValue();
          cur.url = url;
          cur.value = sc.nextDouble();
          pq.offer(cur);
        }
      }
    }
    br.close();
  }
Exemplo n.º 19
0
  private static List<Double> getTopN(INDArray vec, int N) {
    ArrayComparator comparator = new ArrayComparator();
    PriorityQueue<Double[]> queue = new PriorityQueue(vec.rows(), comparator);

    for (int j = 0; j < vec.length(); j++) {
      final Double[] pair = new Double[] {vec.getDouble(j), (double) j};
      if (queue.size() < N) {
        queue.add(pair);
      } else {
        Double[] head = queue.peek();
        if (comparator.compare(pair, head) > 0) {
          queue.poll();
          queue.add(pair);
        }
      }
    }
    List<Double> lowToHighSimLst = new ArrayList();

    while (!queue.isEmpty()) {
      double ind = queue.poll()[1];
      lowToHighSimLst.add(ind);
    }
    return Lists.reverse(lowToHighSimLst);
  }
  /** ***************************************************************************** */
  void addEntry(String s) {
    // System.err.println("TRACX: " + s);
    if (trace_writer != null) trace_writer.println(s);

    char s0 = s.charAt(0);
    if (s0 == 'T') { // THREAD
      if (thread_entries != null) {
        for (TraceEntry te : thread_entries) pending_entries.add(te);
        thread_entries = null;
      }
      StringTokenizer tok = new StringTokenizer(s);
      tok.nextToken();
      int id = Integer.parseInt(tok.nextToken());
      current_thread = thread_map.get(id);
      if (current_thread == null) {
        int tid = Integer.parseInt(tok.nextToken());
        String tnm = tok.nextToken("\n");
        current_thread = new ThreadData(++thread_counter, tid, tnm);
        thread_map.put(id, current_thread);
      }
      thread_entries = new ArrayList<TraceEntry>();
    } else if (s0 == 'D') { // DONE
      if (trace_writer != null) trace_writer.flush();
      if (thread_entries != null) {
        for (TraceEntry te : thread_entries) pending_entries.add(te);
        thread_entries = null;
      }
      StringTokenizer tok = new StringTokenizer(s);
      tok.nextToken();
      long time = Long.parseLong(tok.nextToken());
      if (next_time != 0) {
        int ct = 0;
        // System.err.println("TRACE: Pending size = " + pending_entries.size());
        while (!pending_entries.isEmpty() && pending_entries.peek().getTime() < next_time) {
          TraceEntry te = pending_entries.remove();
          ++ct;
          outputEntry(te);
        }
        if (ct > 0) {
          for (BdynEventUpdater eu : update_listeners) {
            eu.eventsAdded();
          }
        }
        end_time = Math.max(next_time, end_time);
      }
      next_time = time;
    } else if (s0 == 'S') {
      if (cpu_time == null) {
        StringTokenizer tok = new StringTokenizer(s);
        tok.nextToken();
        cpu_time = Boolean.parseBoolean(tok.nextToken());
      }
    } else if (cpu_time != null) {
      TraceEntry te = new TraceEntry(s, current_thread, cpu_time);
      if (thread_entries == null) pending_entries.add(te);
      else {
        thread_entries.add(te);
        if (te.isExit()) {
          int sz = thread_entries.size();
          int loc = te.getEntryLocation();
          if (sz >= 4) {
            TraceEntry t3 = thread_entries.get(sz - 2);
            if (!t3.isExit() && t3.getEntryLocation() == loc) {
              TraceEntry t2 = thread_entries.get(sz - 3);
              if (t2.isExit() && t2.getEntryLocation() == loc) {
                TraceEntry t1 = thread_entries.get(sz - 4);
                if (!t1.isExit()
                    && t1.getEntryLocation() == loc
                    && (te.getTime() - t1.getTime()) < MERGE_TIME) {
                  t1.merge(t2.getTime(), t3.getTime(), te.getTime());
                  thread_entries.remove(sz - 2);
                  thread_entries.remove(sz - 3);
                }
              }
            }
          }
        }
      }
    }
  }
 public static void print() {
   while (pq.peek() != null) {
     System.out.println(pq.remove().url);
   }
 }
 public static void add(UrlValue url) {
   if (url != null && !url.url.trim().equals("") && !visitedUrl.contains(url.url)) {
     url.url = url.url.trim();
     pq.offer(url);
   }
 }
  public static void main(String[] args) throws Exception {
    int V, E, s, u, v, w;

    /* // Graph in Figure 4.17
    5 7 2
    2 1 2
    2 3 7
    2 0 6
    1 3 3
    1 4 6
    3 4 5
    0 4 1
        */

    Scanner sc = new Scanner(System.in);
    V = sc.nextInt();
    E = sc.nextInt();
    s = sc.nextInt();

    AdjList.clear();
    for (int i = 0; i < V; i++) {
      ArrayList<IntegerPair> Neighbor = new ArrayList<IntegerPair>();
      AdjList.add(Neighbor); // add neighbor list to Adjacency List
    }

    for (int i = 0; i < E; i++) {
      u = sc.nextInt();
      v = sc.nextInt();
      w = sc.nextInt();
      AdjList.get(u).add(new IntegerPair(v, w)); // first time using weight
    }

    // Dijkstra routine
    ArrayList<Integer> dist = new ArrayList<>();
    // INF = 1*10^9 not MAX_INT to avoid overflow
    dist.addAll(Collections.nCopies(V, INF));
    dist.set(s, 0);
    PriorityQueue<IntegerPair> pq =
        new PriorityQueue<IntegerPair>(
            1,
            new Comparator<IntegerPair>() { // overriding the compare method
              public int compare(IntegerPair i, IntegerPair j) {
                return i.dfs - j.dfs;
              }
            });
    pq.offer(new IntegerPair(s, 0)); // sort based on increasing distance

    while (!pq.isEmpty()) { // main loop
      IntegerPair top = pq.poll(); // greedy: pick shortest unvisited vertex
      int d = top.dfs;
      u = top.vn;
      if (d > dist.get(u)) continue; // We want to process vertex u only once!
      Iterator it = AdjList.get(u).iterator();
      while (it.hasNext()) { // all outgoing edges from u
        IntegerPair p = (IntegerPair) it.next();
        v = p.vn;
        int weight_u_v = p.dfs;
        if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax
          // (note: Record SP spanning tree here if needed. This is similar)
          dist.set(v, dist.get(u) + weight_u_v); // relax
          pq.offer(new IntegerPair(v, dist.get(v))); //   (as printpath in BFS)
          // enqueue this neighbor regardless whether it is already in pq or not
        }
      }
    }

    for (int i = 0; i < V; i++) // index + 1 for final answer
    System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist.get(i));
  }
Exemplo n.º 24
0
  // Sorts Both the file , individually
  // irrespective of their size.
  public static void initialize(
      String table1, String table1_join_col, String table2, String table2_join_col) {

    // System.out.println(DBSystem.PATH_FOR_DATA);
    // System.out.println(table1);

    tab1 = table1;
    tab2 = table2;

    for (Table t : DBSystem.tableList) {

      if (t.getName().equalsIgnoreCase(table1)) {
        table1JoinColIndex = t.getColumnNum().get(table1_join_col);
        table1JoinColType = t.getColumnData().get(table1_join_col);
        table1Lines = t.getLines();
        t1 = t;
      } else if (t.getName().equalsIgnoreCase(table2)) {
        table2JoinColIndex = t.getColumnNum().get(table2_join_col);
        table2JoinColType = t.getColumnData().get(table2_join_col);
        table2Lines = t.getLines();
        t2 = t;
      }
    }
    // System.out.println(table1 + " - " + table1_join_col + " - " + table1JoinColIndex + " - " +
    // table1JoinColType);
    // System.out.println(table2 + " - " + table2_join_col + " - " + table2JoinColIndex + " - " +
    // table2JoinColType);

    if (!table1JoinColType.equalsIgnoreCase(table2JoinColType)) {
      System.out.println("Both the tables must have similar join types");
      System.exit(1);
    }

    int numberOfcolumnsForJoin = 2; // For Joining Two tables

    // Sort the columns used for join
    for (int k = 0; k < numberOfcolumnsForJoin; k++) {
      String tab = null;
      String tabColType = null;
      int tabColIndex = 0;
      int tLines = 0;

      if (k == 0) {
        // Sorting table 1.
        tab = table1;
        tabColType = table1JoinColType;
        tabColIndex = table1JoinColIndex;
        tLines = table1Lines;
      } else if (k == 1) {
        // Sorting table 2
        tab = table2;
        tabColType = table2JoinColType;
        tabColIndex = table2JoinColIndex;
        tLines = table2Lines;
      }

      Comparator<String> cmp = new SortingComparator(tabColIndex, tabColType);
      PriorityQueue<String> priorityQueue = new PriorityQueue<String>(10, cmp);

      int remainingBufferSize = MAX_MEM_TO_USE;
      int fileCount = 1;
      String line;
      int inOutFlag = 0;

      for (int i = 0; i < tLines; i++) {
        line = DBSystem.getRecord(tab, i);

        // System.out.println(line);
        // String cols [] = line.split(",");

        remainingBufferSize -= line.getBytes().length;
        if (remainingBufferSize >= 0) {
          priorityQueue.add(line);
          inOutFlag = 1;
        } else {
          // write to file
          FileWriter fileWriter = null;
          // System.out.println("Written");
          try {
            // String fileName = setBlockFile(fileCount,table1);
            // System.out.println(fileName);
            fileWriter = new FileWriter(new File(setBlockFile(fileCount, tab)));
            int siz = priorityQueue.size();
            // System.out.println(siz);
            for (int j = 0; j < siz; j++) {
              fileWriter.write(priorityQueue.poll().toString());
              // System.out.println(priorityQueue.poll().toString());
              fileWriter.write("\n");
            }
            fileCount++;
          } catch (IOException e) {
            e.printStackTrace();
          } finally {
            try {
              fileWriter.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          // set remainingSize back to MAX_MEM_TO_USE
          remainingBufferSize = MAX_MEM_TO_USE;
          // current read line
          priorityQueue.add(line);
          remainingBufferSize -= line.getBytes().length;
          inOutFlag = 0;
        }
      }

      if (inOutFlag == 1) {
        FileWriter fw = null;

        try {
          fw = new FileWriter(new File(setBlockFile(fileCount, tab)));
          int psiz = priorityQueue.size();
          for (int j = 0; j < psiz; j++) {
            fw.write(priorityQueue.poll().toString());
            // System.out.println(priorityQueue.poll().toString());
            fw.write("\n");
          }

        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          try {
            fw.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

      if (k == 0) table1_tempfileCount = fileCount;
      if (k == 1) table2_tempfileCount = fileCount;
    }

    // Begin the merging process for both the files.

    // System.out.println(table1_tempfileCount);
    // System.out.println(table2_tempfileCount);

    // Merging Process
    SortedMergeJoin sortedMergeJoin =
        new SortedMergeJoin(
            table1,
            table1_tempfileCount,
            table1JoinColIndex,
            table1JoinColType,
            table2,
            table2_tempfileCount,
            table2JoinColIndex,
            table2JoinColType);
    sortedMergeJoin.execute();
  }
Exemplo n.º 25
0
  public static void main(String args[]) throws IOException {

    String text = "C:\\Users\\Roshan Rajan\\Desktop\\squaredance.txt";
    String gender = "";
    PriorityQueue<String> men = new PriorityQueue<String>();
    PriorityQueue<String> women = new PriorityQueue<String>();
    BufferedReader input = new BufferedReader(new FileReader(text));
    String line = null;
    while ((line = input.readLine()) != null) {
      gender = line.substring(0, 1);
      if (gender.equals("M")) men.add(line.substring(2));
      else women.add(line.substring(2));
    }
    input.close();

    while (!men.isEmpty() && !women.isEmpty()) {
      System.out.println("The couples are ");
      System.out.println(men.poll() + " is Dancing with " + women.poll());
    }
    if (men.isEmpty()) {
      System.out.println(women.size() + " girls are Waiting to Dance");
      System.out.println(women.peek() + " is the first one waiting");
    }
    if (women.isEmpty()) {
      System.out.println(men.size() + " guys are Waiting to Dance");
      System.out.println(men.peek() + " is the first one waiting");
    }
  }
Exemplo n.º 26
0
  /**
   * The constructor creates the NodeTable and DirectedGraph taken the information from files
   * lines-gbg.txt and stops-gbg.txt and makes itself visible.
   */
  public ShortRoute(String file) {

    // try to convert to UTF-8 across plattforms to make Swedish chars work
    // System.out.println("charset = " + java.nio.charset.Charset.defaultCharset());
    // MacRoman macintosh  Windows-1252 ISO 8859-1 UTF-8
    try {
      // convert whatever this file is encoded in to UTF-8,
      // kill the exception (can't happen)
      introText =
          new String(
              introText.getBytes(java.nio.charset.Charset.defaultCharset().toString()), "UTF-8");
      felTextStart =
          new String(
              felTextStart.getBytes(java.nio.charset.Charset.defaultCharset().toString()), "UTF-8");
      felTextSlut =
          new String(
              felTextSlut.getBytes(java.nio.charset.Charset.defaultCharset().toString()), "UTF-8");
      frome =
          new String(frome.getBytes(java.nio.charset.Charset.defaultCharset().toString()), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.exit(0);
    }

    // read the graph and draw it in a separate window
    // creates the graph and fills the p-queue "names"
    karta.setLocation(50, 250);
    if (file == null) {
      readAndDrawGraph();
    } else {
      readAndDrawBIGGraph(file);
    }
    System.out.println("Version with sorting fixed"); // debug
    // now to the graphics in the Frame
    // Left part
    // select is a panel for structuring the left part
    // i.e label, textfield for "from", label, textfield for "to"
    JPanel select = new JPanel(new GridLayout(4, 1));
    select.setBackground(Color.yellow);
    select.add(new JLabel("Ange startpunkt !", JLabel.CENTER));
    select.add(from);
    select.add(new JLabel("Ange slutpunkt !", JLabel.CENTER));
    select.add(to);
    from.setBackground(Color.white);
    from.setForeground(Color.blue);
    to.setBackground(Color.white);
    to.setForeground(Color.blue);
    from.addActionListener(this);
    to.addActionListener(this);

    // Middle part
    // route is the middle text area part where messages are displayed
    // give the middle text area a scrollbar to the right
    route = new JTextArea(introText, 12, 40);
    route.setEditable(false);
    JScrollPane routeScrollPane = new JScrollPane(route);
    routeScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    route.setBackground(Color.white);
    route.setForeground(Color.blue);

    // Rigth part
    JLabel head = new JLabel("   ****        Alternativ     *****     ");
    head.setForeground(Color.red);

    // add all stations to the right scrollpane
    // tanken är att dom skall vara valbara men det fungerar inte än
    // En JList vill ha en ListModel som parameter
    // En ListModel är ett interface som implementeras av klassen AbstractListModel
    // DefaultListModel ärver AbstractListModel
    DefaultListModel<String> valList = new DefaultListModel<String>();
    JList<String> alternativ = new JList<String>(valList);
    alternativ.setBackground(Color.white);
    alternativ.setForeground(Color.blue);
    // add a scroll pane to the station list in alternativ
    stationList = new JScrollPane(alternativ);
    // read names from p-queue and load them into the list
    while (!names.isEmpty()) valList.addElement(names.poll());

    // panel for structure
    JPanel valPanel = new JPanel(new BorderLayout());
    valPanel.setBackground(Color.white);
    valPanel.add(head, "North");
    valPanel.add(stationList, "Center");

    // put it all together in the frame
    add(select, "West");
    add(routeScrollPane, "Center");
    add(valPanel, "East");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  } // end ShortRoute
Exemplo n.º 27
0
  // ====================================================================
  // ====================================================================
  private void readAndDrawGraph() {
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File("stops.noBOM.txt"), "UTF-8");
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        /*
        // Denna fix som slår ihop Kålltorp och Torp är förvirrande eftersom de är olika noder i grafen.
        // Tror man att det är samma nod blir resultatet förrvirrande.
        // Till nästa gång: Gör till samma nod med namnet Virginsgatan. Så är det i verkligheten nu.

        				// this is a fix: fixa att Kålltorp och Torp är samma hållplats
        				if ( hpl.equals("Torp") ) {
        					xco += 11;
        					hpl = "   / Torp";
        				}
        */
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File("lines.noBOM.txt"), "UTF-8");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      while (indata.hasNext()) {
        String lineNo = indata.next();
        int antal = indata.nextInt() - 1;
        int from = noderna.find(indata.next()).getNodeNo();
        // hur rita flera linjer mellan 2 noder?
        // enkel inc fungerar inte
        // färgen kunde vara "äkta" dvs linjefärg
        Color color =
            new Color((float) Math.random(), (float) Math.random(), (float) Math.random());
        for (int i = 0; i < antal; i++) {
          int to = noderna.find(indata.next()).getNodeNo();
          grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
          // Draw
          BusStop busFrom = noderna.find(from);
          BusStop busTo = noderna.find(to);
          karta.drawLine(
              busFrom.xpos,
              busFrom.ypos,
              busTo.xpos,
              busTo.ypos,
              color,
              2.0f,
              DrawGraph.Layer.BASE);
          from = to;
        }
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawGraph
 public static void clear() {
   pq.clear();
 }
Exemplo n.º 29
0
 public static void main(String[] args) throws Exception {
   BufferedReader br = new BufferedReader(new FileReader(new File(args[0])));
   BufferedWriter bw = new BufferedWriter(new FileWriter(args[1]));
   int T = Integer.parseInt(br.readLine());
   for (int t = 1; t <= T; t++) {
     br.readLine();
     List<List<Station>> graph = new ArrayList<>();
     int N = Integer.parseInt(br.readLine());
     for (int i = 0; i < N; i++) {
       graph.add(new ArrayList<>());
       String[] line1 = br.readLine().split(" ");
       int SN = Integer.parseInt(line1[0]);
       int W = Integer.parseInt(line1[1]);
       for (int j = 0; j < SN; j++) {
         graph.get(i).add(new Station(i, j, W));
       }
       String[] dist = br.readLine().split(" ");
       for (int j = 0; j < dist.length; j++) {
         int d = Integer.parseInt(dist[j]);
         Station s1 = graph.get(i).get(j);
         Station s2 = graph.get(i).get(j + 1);
         s1.neighbors.put(s2, d);
         s2.neighbors.put(s1, d);
       }
     }
     int tunnelNum = Integer.parseInt(br.readLine());
     for (int i = 0; i < tunnelNum; i++) {
       String[] tunnel = br.readLine().split(" ");
       int l1 = Integer.parseInt(tunnel[0]) - 1;
       int s1 = Integer.parseInt(tunnel[1]) - 1;
       int l2 = Integer.parseInt(tunnel[2]) - 1;
       int s2 = Integer.parseInt(tunnel[3]) - 1;
       int d = Integer.parseInt(tunnel[4]);
       Station sta1 = graph.get(l1).get(s1);
       Station sta2 = graph.get(l2).get(s2);
       sta1.neighbors.put(sta2, d + sta2.waitTime); // add wait time to distance
       sta2.neighbors.put(sta1, d + sta1.waitTime);
       Station sta11 = sta1.cloneForTunnel();
       Station sta22 = sta2.cloneForTunnel();
       graph.get(sta1.lineNo).add(sta11);
       graph.get(sta2.lineNo).add(sta22);
       for (Station st : sta11.neighbors.keySet()) {
         sta2.neighbors.put(
             st,
             d
                 + sta11.neighbors.get(
                     st)); // don't wait, sta11 means go xsfrom sta2 to sta1 than go to other
         // tunnel
       }
       for (Station st : sta22.neighbors.keySet()) {
         sta1.neighbors.put(st, d + sta22.neighbors.get(st));
       }
     }
     int queryNum = Integer.parseInt(br.readLine());
     bw.write("Case: #" + t + ":");
     bw.newLine();
     for (int i = 0; i < queryNum; i++) {
       String[] query = br.readLine().split(" ");
       int l1 = Integer.parseInt(query[0]) - 1;
       int s1 = Integer.parseInt(query[1]) - 1;
       int l2 = Integer.parseInt(query[2]) - 1;
       int s2 = Integer.parseInt(query[3]) - 1;
       Station sta1 = graph.get(l1).get(s1);
       Station sta2 = graph.get(l2).get(s2);
       PriorityQueue<Station> pq = new PriorityQueue<>();
       sta1.dist = sta1.waitTime;
       for (List<Station> line : graph) {
         for (Station st : line) {
           pq.offer(st);
         }
       }
       Set<Station> visited = new HashSet<>();
       visited.add(sta1);
       boolean done = false;
       while (!done && !pq.isEmpty()) {
         Station st = pq.poll();
         for (Station neb : st.neighbors.keySet()) {
           if (!visited.contains(neb)) {
             neb.dist = st.dist + st.neighbors.get(neb);
             if (neb == sta2) { // reference to same object
               done = true;
               break;
             }
             visited.add(neb);
             pq.remove(neb); // because need to let pq update this item's priority level
             pq.offer(neb);
           }
         }
       }
       int ret = sta2.dist == Integer.MAX_VALUE ? -1 : sta2.dist;
       bw.write("" + ret);
       bw.newLine();
     }
   }
   bw.close();
   br.close();
 }
Exemplo n.º 30
0
  public JSONArray Cluster(String wekaFilePath, int clusterNum) throws Exception {
    File inputFile = new File(wekaFilePath);
    ArffLoader arf = new ArffLoader();
    arf.setFile(inputFile);
    Instances originIns = arf.getDataSet();
    Instances insTest = new Instances(originIns);
    insTest.deleteStringAttributes();
    int totalNum = insTest.numInstances();

    // SimpleKMeans sm = new SimpleKMeans();
    EM em = new EM();
    em.setNumClusters(clusterNum);
    MakeDensityBasedClusterer sm = new MakeDensityBasedClusterer();
    sm.setClusterer(em);
    sm.buildClusterer(insTest);

    System.out.println("totalNum:" + insTest.numInstances());
    System.out.println("============================");
    System.out.println(sm.toString());
    Map<Integer, ArrayList<String>> result = new HashMap<Integer, ArrayList<String>>();
    for (int i = 0; i < clusterNum; i++) {
      result.put(i, new ArrayList<String>());
    }

    for (int i = 0; i < totalNum; i++) {
      Instance ins = originIns.instance(i);
      String word = ins.stringValue(0);
      Instance tempIns = new Instance(ins);
      tempIns.deleteAttributeAt(0);
      int cluster = sm.clusterInstance(tempIns);
      result.get(cluster).add(word);
    }

    // print the result
    ArrayList<String> words = new ArrayList<String>();
    JSONArray keyWords = new JSONArray();
    for (int k : result.keySet()) {
      words = result.get(k);
      PriorityQueue<MyTerm> clusterQueue = new PriorityQueue<MyTerm>(1, MyTermCompare);
      for (int i = 0; i < words.size(); i++) {
        String s = words.get(i);
        assert linkMap.containsKey(s);
        int freq = linkMap.get(s).totalFreq;
        clusterQueue.add(linkMap.get(s));
        words.set(i, "(" + s + ":" + freq + ")");
      }

      JSONArray clusterArray = new JSONArray();
      int num = clusterQueue.size() / 10 + 1; // 5%
      int totalFreq = 0;
      int totalLength = 0;
      for (int i = 0; i < num && !clusterQueue.isEmpty(); ) {
        JSONObject mem = new JSONObject();
        MyTerm myTerm = clusterQueue.poll();
        String word = myTerm.originTrem.text();
        if (word.length() == 1) {
          continue;
        }
        mem.put("text", word);
        mem.put("freq", myTerm.totalFreq);
        clusterArray.put(mem);
        i++;
        totalFreq += myTerm.totalFreq;
        totalLength += word.length();
      }

      double averFreq = totalFreq * 1.0 / num;
      double averLength = totalLength * 1.0 / num;
      int count = 0;
      while (!clusterQueue.isEmpty() && count < num) {
        MyTerm myTerm = clusterQueue.poll();
        String word = myTerm.originTrem.text();
        int freq = myTerm.totalFreq;
        int times = (int) (word.length() / averFreq) + 1;
        if (freq > averFreq / times) {
          JSONObject mem = new JSONObject();
          mem.put("text", word);
          mem.put("freq", freq);
          mem.put("extra", true);
          clusterArray.put(mem);
        }
      }

      keyWords.put(clusterArray);
      System.out.println(
          "cluster" + k + ":" + words.size() + ":\t" + (int) (words.size() * 1.0 / totalNum * 100));
      if (result.get(k).size() < 100) {
        System.out.println(result.get(k));
      }
    }
    // System.out.println("errorNum:"+errorNum);
    return keyWords;
  }