Example #1
0
 public void solve(InputReader in, OutputWriter out) {
   int n = in.nextInt();
   int[][] g = new int[n][n];
   for (int i = 0; i < n; i++) {
     for (int j = 0; j < n; j++) {
       g[i][j] = in.nextInt();
     }
   }
   Queue<int[]> queue =
       new PriorityQueue<int[]>(
           1,
           new Comparator<int[]>() {
             @Override
             public int compare(int[] o1, int[] o2) {
               return o1[1] - o2[1];
             }
           });
   queue.add(new int[] {0, 0});
   boolean[] visited = new boolean[n];
   int res = 0;
   while (!queue.isEmpty()) {
     int[] head = queue.remove();
     int node = head[0];
     int dist = head[1];
     if (!visited[node]) {
       res += dist;
       visited[node] = true;
       for (int i = 0; i < n; i++) {
         if (!visited[i]) {
           queue.add(new int[] {i, g[node][i]});
         }
       }
     }
   }
   out.println(res);
 }
  public int printSmiles(int smiles) {
    boolean[][] visited = new boolean[2001][2001];
    Queue<Integer> posQ = new LinkedList<>();
    Queue<Integer> copyQ = new LinkedList<>();
    Queue<Integer> countQ = new LinkedList<>();
    posQ.add(1);
    copyQ.add(0);
    countQ.add(0);
    while (true) {
      int pos = posQ.poll();
      int copy = copyQ.poll();
      if (pos == smiles) break;
      int count = countQ.poll();

      if (visited[pos][copy]) continue;
      visited[pos][copy] = true;

      if (pos < smiles) {
        // copy
        posQ.add(pos);
        copyQ.add(pos);
        countQ.add(count + 1);
        // paste
        posQ.add(pos + copy);
        copyQ.add(copy);
        countQ.add(count + 1);
      }

      // delete
      if (pos - 1 >= 0) {
        posQ.add(pos - 1);
        copyQ.add(copy);
        countQ.add(count + 1);
      }
    }
    return countQ.poll();
  }