Example #1
1
 public int minimumPrice(long[] dread, int[] price) {
   int n = dread.length;
   int m = n << 1;
   long[] maximum = new long[m + 1];
   Arrays.fill(maximum, 0);
   for (int i = 0; i < n; ++i) {
     long[] new_maximum = new long[m + 1];
     Arrays.fill(new_maximum, -1);
     for (int j = 0; j <= m; ++j) {
       if (maximum[j] != -1) {
         if (maximum[j] >= dread[i]) {
           new_maximum[j] = Math.max(new_maximum[j], maximum[j]);
         }
         if (j + price[i] <= m) {
           new_maximum[j + price[i]] = Math.max(new_maximum[j + price[i]], maximum[j] + dread[i]);
         }
       }
     }
     maximum = new_maximum;
   }
   int answer = 0;
   while (maximum[answer] == -1) {
     answer++;
   }
   return answer;
 }
Example #2
1
 public static void main(String[] args) throws IOException {
   in = new Reader();
   out = new PrintWriter(System.out, true);
   for (; ; ) {
     int n = in.nextInt();
     if (n == 0) break;
     int[] arr1 = new int[n];
     for (int i = 0; i < n; i++) arr1[i] = in.nextInt();
     int m = in.nextInt();
     int[] arr2 = new int[m];
     for (int i = 0; i < m; i++) arr2[i] = in.nextInt();
     int idx1 = 0, idx2 = 0, sum1 = 0, sum2 = 0, sum = 0;
     for (; ; ) {
       sum1 += arr1[idx1];
       while (idx2 < m && arr1[idx1] > arr2[idx2]) sum2 += arr2[idx2++];
       if (idx2 == m) {
         idx1++;
         break;
       }
       if (arr1[idx1] == arr2[idx2]) {
         sum2 += arr2[idx2++];
         sum += Math.max(sum1, sum2);
         sum1 = sum2 = 0;
       }
       idx1++;
       if (idx1 == n) break;
     }
     while (idx1 < n) sum1 += arr1[idx1++];
     while (idx2 < m) sum2 += arr2[idx2++];
     sum += Math.max(sum1, sum2);
     out.println(sum);
   }
 }
 public CatchExceptionTest(
     TestCase testCase, final boolean isVararg, final int argsCount, final int catchDrops) {
   this.testCase = testCase;
   this.dropped = catchDrops;
   if (Helper.IS_VERBOSE) {
     System.out.printf(
         "CatchException::CatchException(%s, isVararg=%b " + "argsCount=%d catchDrops=%d)%n",
         testCase, isVararg, argsCount, catchDrops);
   }
   MethodHandle thrower = testCase.thrower;
   int throwerLen = thrower.type().parameterCount();
   List<Class<?>> classes;
   int extra = Math.max(0, argsCount - throwerLen);
   classes = getThrowerParams(isVararg, extra);
   this.argsCount = throwerLen + classes.size();
   thrower = Helper.addTrailingArgs(thrower, this.argsCount, classes);
   if (isVararg && argsCount > throwerLen) {
     MethodType mt = thrower.type();
     Class<?> lastParam = mt.parameterType(mt.parameterCount() - 1);
     thrower = thrower.asVarargsCollector(lastParam);
   }
   this.thrower = thrower;
   this.dropped = Math.min(this.argsCount, catchDrops);
   catcher = testCase.getCatcher(getCatcherParams());
   nargs = Math.max(2, this.argsCount);
 }
  public static int maxProduct(int[] A) {
    if (A.length == 0) {
      return 0;
    }
    if (A.length == 1 && A[0] < 0) {
      return A[0];
    }
    int max_product = 0;

    int current_max = 0;
    int current_min = 0;

    int prev_max = 1;
    int prev_min = 1;

    for (int i = 0; i < A.length; i++) {
      current_max = Math.max(Math.max(prev_max * A[i], prev_min * A[i]), A[i]);
      current_min = Math.min(Math.min(prev_max * A[i], prev_max * A[i]), A[i]);

      max_product = Math.max(max_product, current_max);

      prev_max = current_max;
      prev_min = current_min;
    }
    return max_product;
  }
  public void paint(Graphics gg) {
    int faceSize = Math.min(getWidth() - 4, getHeight() - 4);
    if (face == null)
      face =
          new PADFaceMapped(
              Math.max(2, (getWidth() - faceSize) / 2),
              Math.max(2, (getHeight() - faceSize) / 2),
              faceSize);
    if (buffer == null) {
      im = this.createImage(getWidth(), getHeight());
      buffer = im.getGraphics();
    }
    super.paint(buffer);

    buffer.setColor(new Color(255, 255, 255, 0));
    buffer.fillRect(0, 0, im.getWidth(null), im.getHeight(null));

    face.setDimensions(
        Math.max(2, (getWidth() - faceSize) / 2),
        Math.max(2, (getHeight() - faceSize) / 2),
        faceSize);
    face.paint(buffer);

    // draw buffer to screen
    gg.drawImage(im, 0, 0, null, null);
  }
Example #6
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    TreeMap<Long, Long> tmap = new TreeMap<>();
    long res = 0;
    while (t-- > 0) {
      res = 0;
      int n = in.nextInt();
      long m = in.nextLong();
      tmap.clear();
      long[] arr = new long[n];
      res = in.nextLong();
      arr[0] = res % m;
      res = Long.MIN_VALUE;
      tmap.put(arr[0], arr[0]);
      for (int i = 1; i < arr.length; i++) {
        arr[i] = in.nextLong();
        arr[i] %= m;
        arr[i] += arr[i - 1];
        arr[i] %= m;

        if (tmap.higherEntry(arr[i]) == null) {
          res = Math.max(res, arr[i]);
          tmap.put(arr[i], arr[i]);
          continue;
        }
        long val = tmap.higherEntry(arr[i]).getValue();
        res = Math.max(res, (arr[i] - val + m) % m);
        tmap.put(arr[i], arr[i]);
      }

      System.out.println(res);
    }
  }
    private Pair<MutableTextRange, StringBuffer> getFragmentByRange(int start, final int length) {
      final StringBuffer fragmentBuffer = new StringBuffer();
      int end = start + length;

      // restoring buffer and remove all subfragments from the list
      int documentOffset = 0;
      int effectiveOffset = 0;

      Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator();
      while (iterator.hasNext() && effectiveOffset <= end) {
        final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
        final MutableTextRange range = pair.getFirst();
        final StringBuffer buffer = pair.getSecond();
        int effectiveFragmentEnd = range.getStartOffset() + buffer.length();

        if (range.getStartOffset() <= start && effectiveFragmentEnd >= end) return pair;

        if (effectiveFragmentEnd >= start) {
          final int effectiveStart = Math.max(effectiveOffset, start);
          if (range.getStartOffset() > start) {
            fragmentBuffer.append(
                myDocument.getCharsSequence(),
                effectiveStart - effectiveOffset + documentOffset,
                Math.min(range.getStartOffset(), end) - effectiveOffset + documentOffset);
          }
          if (end >= range.getStartOffset()) {
            fragmentBuffer.append(buffer);
            end =
                end > effectiveFragmentEnd
                    ? end - (buffer.length() - range.getLength())
                    : range.getEndOffset();
            effectiveFragmentEnd = range.getEndOffset();
            start = Math.min(start, range.getStartOffset());
            iterator.remove();
          }
        }

        documentOffset += range.getEndOffset() - effectiveOffset;
        effectiveOffset = effectiveFragmentEnd;
      }

      if (effectiveOffset < end) {
        final int effectiveStart = Math.max(effectiveOffset, start);
        fragmentBuffer.append(
            myDocument.getCharsSequence(),
            effectiveStart - effectiveOffset + documentOffset,
            end - effectiveOffset + documentOffset);
      }

      MutableTextRange newRange = new MutableTextRange(start, end);
      final Pair<MutableTextRange, StringBuffer> pair =
          new Pair<MutableTextRange, StringBuffer>(newRange, fragmentBuffer);
      for (Pair<MutableTextRange, StringBuffer> affectedFragment : myAffectedFragments) {
        MutableTextRange range = affectedFragment.getFirst();
        assert end <= range.getStartOffset() || range.getEndOffset() <= start
            : "Range :" + range + "; Added: " + newRange;
      }
      myAffectedFragments.add(pair);
      return pair;
    }
Example #8
0
  public static void main(String[] args) {
    FastScanner in = new FastScanner(System.in);
    int n = in.nextInt();
    int[] s = new int[n + 5];
    int[] s2 = new int[n + 5];
    for (int i = 1; i <= n; i++) {
      s[i] = in.nextInt();
      s2[n - i + 1] = s[i];
    }

    int[] stack = new int[n + 5];
    int size = 0;
    int answer = 0;
    for (int i = 1; i <= n; i++) {
      while (size > 0 && stack[size - 1] < s[i]) size--;

      stack[size++] = s[i];

      if (size >= 2) answer = Math.max(answer, stack[size - 1] ^ stack[size - 2]);
    }
    size = 0;
    for (int i = 1; i <= n; i++) {
      while (size > 0 && stack[size - 1] < s2[i]) size--;

      stack[size++] = s2[i];

      if (size >= 2) answer = Math.max(answer, stack[size - 1] ^ stack[size - 2]);
    }
    System.out.println(answer);
  }
Example #9
0
 public int filterRGB(int x, int y, int rgb) {
   int r = ((rgb >> 16) & 0xff);
   int g = ((rgb >> 8) & 0xff);
   int b = (rgb & 0xff);
   int gray = Math.max(Math.max(r, g), b);
   return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0);
 }
  /**
   * Calculates the min and max boundaries of the structure after it has been transformed into its
   * canonical orientation.
   */
  private void calcBoundaries() {
    minBoundary.x = Double.MAX_VALUE;
    maxBoundary.x = Double.MIN_VALUE;
    minBoundary.y = Double.MAX_VALUE;
    maxBoundary.x = Double.MIN_VALUE;
    minBoundary.z = Double.MAX_VALUE;
    maxBoundary.z = Double.MIN_VALUE;
    xzRadiusMax = Double.MIN_VALUE;

    Point3d probe = new Point3d();

    for (Point3d[] list : subunits.getTraces()) {
      for (Point3d p : list) {
        probe.set(p);
        transformationMatrix.transform(probe);

        minBoundary.x = Math.min(minBoundary.x, probe.x);
        maxBoundary.x = Math.max(maxBoundary.x, probe.x);
        minBoundary.y = Math.min(minBoundary.y, probe.y);
        maxBoundary.y = Math.max(maxBoundary.y, probe.y);
        minBoundary.z = Math.min(minBoundary.z, probe.z);
        maxBoundary.z = Math.max(maxBoundary.z, probe.z);
        xzRadiusMax = Math.max(xzRadiusMax, Math.sqrt(probe.x * probe.x + probe.z * probe.z));
      }
    }
    //		System.out.println("MinBoundary: " + minBoundary);
    //		System.out.println("MaxBoundary: " + maxBoundary);
    //		System.out.println("zxRadius: " + xzRadiusMax);
  }
Example #11
0
  public static void doIt() throws Exception {
    Scanner scanner = new Scanner(System.in);
    Integer currentBalance = scanner.nextInt();
    int removeLast, removePenultimate;
    StringBuffer buf = new StringBuffer();

    ArrayList<Character> chars = new ArrayList<Character>();
    for (Character c : currentBalance.toString().toCharArray()) chars.add(c);

    ArrayList<Character> c1 = (ArrayList<Character>) chars.clone();
    c1.remove(c1.size() - 1);

    for (Character cc : c1) buf.append(cc);

    removeLast = new Integer(buf.toString());
    buf = new StringBuffer();

    ArrayList<Character> c2 = (ArrayList<Character>) chars.clone();
    c2.remove(c2.size() - 2);

    for (Character cc : c2) buf.append(cc);
    removePenultimate = new Integer(buf.toString());

    System.out.println(Math.max(currentBalance, Math.max(removeLast, removePenultimate)));
  }
Example #12
0
  public Message(String message) {
    Vector indexes = new Vector();
    int pos1 = message.indexOf(NMC_STATUS);
    if (pos1 != -1) {
      indexes.addElement(new Index(NMC_STATUS, pos1));
    }

    int pos2 = message.indexOf(NMC_ERRTYPE);
    if (pos2 != -1) {
      indexes.addElement(new Index(NMC_ERRTYPE, pos2));
    }

    int pos3 = message.indexOf(NMC_ERRINFO);
    if (pos3 != -1) {
      indexes.addElement(new Index(NMC_ERRINFO, pos3));
    }

    int pos4 = message.indexOf(NMC_ERRDETAIL);
    if (pos4 != -1) {
      indexes.addElement(new Index(NMC_ERRDETAIL, pos4));
    }

    int pos5 = message.indexOf(NMC_DESCRIPTION);
    if (pos5 != -1) {
      indexes.addElement(new Index(NMC_DESCRIPTION, pos5));
    }

    int extraIndex =
        message.indexOf('\n', Math.max(Math.max(Math.max(pos1, pos2), Math.max(pos3, pos4)), pos5));
    if (extraIndex != -1) {
      NMC_Extra = message.substring(extraIndex + 1, message.length());

      /* temp solution until Yu-Jen can think up another header schema */
      NMC_Extra = KeyCertUtility.replace(NMC_Extra, "Content-type: text/html", "");
    }
    indexes.addElement(new Index(NMC_EXTRA, extraIndex + 1));

    int size = indexes.size();
    for (int i = 0; i < size - 1; i++) {
      Index beginIndex = (Index) (indexes.elementAt(i));
      Index endIndex = (Index) (indexes.elementAt(i + 1));
      if (beginIndex.getIndexValue().equals(NMC_STATUS)) {
        String val =
            message.substring(beginIndex.getPos() + NMC_STATUS.length(), endIndex.getPos());
        NMC_Status = Integer.parseInt(val.trim());
      } else if (beginIndex.getIndexValue().equals(NMC_DESCRIPTION)) {
        NMC_Description =
            message.substring(beginIndex.getPos() + NMC_DESCRIPTION.length(), endIndex.getPos());
      } else if (beginIndex.getIndexValue().equals(NMC_ERRTYPE)) {
        NMC_ErrType =
            message.substring(beginIndex.getPos() + NMC_ERRTYPE.length(), endIndex.getPos());
      } else if (beginIndex.getIndexValue().equals(NMC_ERRINFO)) {
        NMC_ErrInfo =
            message.substring(beginIndex.getPos() + NMC_ERRINFO.length(), endIndex.getPos());
      } else if (beginIndex.getIndexValue().equals(NMC_ERRDETAIL)) {
        NMC_ErrDetail =
            message.substring(beginIndex.getPos() + NMC_ERRDETAIL.length(), endIndex.getPos());
      }
    }
  }
Example #13
0
  public int getCount(int[] B, String operators) {
    long INF = 1L << 50;
    long min = 1;
    long max = INF;

    for (int i = 0; i < B.length; i++) {
      if (min > max) {
        break;
      }

      long mn = 0;
      long mx = 0;

      if (operators.charAt(i) == '-') {
        mn = Math.max(1, min - B[i]);
        mx = (max == INF) ? INF : max - B[i];
      } else {
        mx = B[i] - min;
        mn = Math.max(B[i] - max, 1);
      }

      min = mn;
      max = mx;
    }

    if (max < min) {
      return 0;
    }
    if (max == INF) {
      return -1;
    }

    return (int) (max - min + 1);
  }
Example #14
0
 private float getFloorHeight() {
   float h00 = getHeight();
   float h10 = getMap().getTile(this, 1, 0) != null ? getMap().getTile(this, 1, 0).getHeight() : 0;
   float h01 = getMap().getTile(this, 0, 1) != null ? getMap().getTile(this, 0, 1).getHeight() : 0;
   float h11 = getMap().getTile(this, 1, 1) != null ? getMap().getTile(this, 1, 1).getHeight() : 0;
   return Math.max(Math.max(h00, h10), Math.max(h01, h11));
 }
Example #15
0
  /**
   * Get the bounding rectangle
   *
   * @return minimum bounding rectangle
   */
  public BoundingRectangle2D getBounds() {
    if (boundsChanged == true) {
      boolean first = true;
      double minX = 0;
      double maxX = 0;
      double minY = 0;
      double maxY = 0;

      for (Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
        Vector2D vertex = (Vector2D) e.nextElement();
        if (first) {
          minX = vertex.getX();
          maxX = vertex.getX();
          minY = vertex.getY();
          maxY = vertex.getY();
          first = false;
        } else {
          minX = Math.min(minX, vertex.getX());
          maxX = Math.max(maxX, vertex.getX());
          minY = Math.min(minY, vertex.getY());
          maxY = Math.max(maxY, vertex.getY());
        }
      }

      bounds.set(minX, minY, Math.abs(maxX - minX), Math.abs(maxY - minY));

      boundsChanged = false;
    }

    return bounds;
  }
Example #16
0
  /**
   * Assigns sequential identifiers to the provided <code>clusters</code> (and their sub-clusters).
   * If a cluster already has an identifier, the identifier will not be changed.
   *
   * @param clusters Clusters to assign identifiers to.
   * @throws IllegalArgumentException if the provided clusters contain non-unique identifiers
   */
  public static void assignClusterIds(Collection<Cluster> clusters) {
    final ArrayList<Cluster> flattened = Lists.newArrayListWithExpectedSize(clusters.size());

    flatten(flattened, clusters);

    synchronized (clusters) {
      final HashSet<Integer> ids = Sets.newHashSet();

      // First, find the start value for the id and check uniqueness of the ids
      // already provided.
      int maxId = Integer.MIN_VALUE;
      for (final Cluster cluster : flattened) {
        if (cluster.id != null) {
          if (!ids.add(cluster.id)) {
            throw new IllegalArgumentException("Non-unique cluster id found: " + cluster.id);
          }
          maxId = Math.max(maxId, cluster.id);
        }
      }

      // We'd rather start with 0
      maxId = Math.max(maxId, -1);

      // Assign missing ids
      for (final Cluster c : flattened) {
        if (c.id == null) {
          c.id = ++maxId;
        }
      }
    }
  }
Example #17
0
 // pretty print Matrix(2D array of doubles)
 public static String pprint(double[][] arr,DecimalFormat dformat) {
   int colDim = 0;
   for( double[] line : arr )
     colDim = Math.max(colDim, line.length);
   StringBuilder sb = new StringBuilder();
   int max_width = 0;
   int[] ilengths = new int[colDim];
   Arrays.fill(ilengths, -1);
   for( double[] line : arr ) {
     for( int c = 0; c < line.length; ++c ) {
       double d = line[c];
       String dStr = dformat.format(d);
       if( dStr.indexOf('.') == -1 ) dStr += ".0";
       ilengths[c] = Math.max(ilengths[c], dStr.indexOf('.'));
       int prefix = (d >= 0 ? 1 : 2);
       max_width = Math.max(dStr.length() + prefix, max_width);
     }
   }
   for( double[] line : arr ) {
     for( int c = 0; c < line.length; ++c ) {
       double d = line[c];
       String dStr = dformat.format(d);
       if( dStr.indexOf('.') == -1 ) dStr += ".0";
       for( int x = dStr.indexOf('.'); x < ilengths[c] + 1; ++x )
         sb.append(' ');
       sb.append(dStr);
       if( dStr.indexOf('.') == -1 ) sb.append('.');
       for( int i = dStr.length() - Math.max(0, dStr.indexOf('.')); i <= 5; ++i )
         sb.append('0');
     }
     sb.append("\n");
   }
   return sb.toString();
 }
 /**
  * Creates a mapping by merging two mappings. There must be no clashes.
  *
  * <p>Unlike {@link #append}, sources and targets are not shifted.
  *
  * <p>For example, <code>merge({0:0, 1:1}, {2:2, 3:3, 4:4})</code> yields <code>
  * {0:0, 1:1, 2:2, 3:3, 4:4}</code>. <code>merge({0:0, 1:1}, {1:2, 2:3})</code> throws, because
  * there are two entries with source=1.
  */
 public static TargetMapping merge(TargetMapping mapping0, TargetMapping mapping1) {
   final int s0 = mapping0.getSourceCount();
   final int s1 = mapping1.getSourceCount();
   final int sMin = Math.min(s0, s1);
   final int sMax = Math.max(s0, s1);
   final int t0 = mapping0.getTargetCount();
   final int t1 = mapping1.getTargetCount();
   final int tMax = Math.max(t0, t1);
   final TargetMapping mapping = create(MappingType.INVERSE_SURJECTION, sMax, tMax);
   for (int s = 0; s < sMin; s++) {
     int t = mapping0.getTargetOpt(s);
     if (t >= 0) {
       mapping.set(s, t);
       assert mapping1.getTargetOpt(s) < 0;
     } else {
       t = mapping1.getTargetOpt(s);
       if (t >= 0) {
         mapping.set(s, t);
       }
     }
   }
   for (int s = sMin; s < sMax; s++) {
     int t = s < s0 ? mapping0.getTargetOpt(s) : -1;
     if (t >= 0) {
       mapping.set(s, t);
       assert mapping1.getTargetOpt(s) < 0;
     } else {
       t = s < s1 ? mapping1.getTargetOpt(s) : -1;
       if (t >= 0) {
         mapping.set(s, t);
       }
     }
   }
   return mapping;
 }
  private void assertMatchEquals(List<Completion> res, String... expected) {
    String[] result = new String[res.size()];
    for (int i = 0; i < res.size(); i++) {
      result[i] = res.get(i).toString();
    }

    if (!Arrays.equals(stripScore(expected), stripScore(result))) {
      int colLen = Math.max(maxLen(expected), maxLen(result));

      StringBuilder b = new StringBuilder();
      String format = "%" + colLen + "s  " + "%" + colLen + "s\n";
      b.append(String.format(Locale.ROOT, format, "Expected", "Result"));
      for (int i = 0; i < Math.max(result.length, expected.length); i++) {
        b.append(
            String.format(
                Locale.ROOT,
                format,
                i < expected.length ? expected[i] : "--",
                i < result.length ? result[i] : "--"));
      }

      System.err.println(b.toString());
      fail("Expected different output:\n" + b.toString());
    }
  }
 @BeforeClass
 public void setUp() {
   nonOverlappingExomeIntervals = new ArrayList<>(100);
   final Random rdn =
       new Random(13); // some "random" but fixed seed to make sure errors are deterministic.
   for (int i = 0; i < ExomeToolsTestUtils.REFERENCE_DICTIONARY.size(); i++) {
     int current = 0;
     final SAMSequenceRecord sequence = ExomeToolsTestUtils.REFERENCE_DICTIONARY.getSequence(i);
     while (current < sequence.getSequenceLength()) {
       int start =
           current
               + Math.max(
                   minimumExonIntergapSize,
                   (int)
                       Math.round(
                           rdn.nextGaussian() * sdExonIntergapSize + averageExonIntergapSize));
       if (start >= sequence.getSequenceLength()) {
         break;
       }
       int size =
           Math.max(
               minimumExonSize,
               (int) Math.round(rdn.nextGaussian() * sdExonSize + averageExonSize));
       int stop = start + size - 1;
       if (stop >= sequence.getSequenceLength()) {
         break;
       }
       nonOverlappingExomeIntervals.add(
           ExomeToolsTestUtils.createInterval(sequence.getSequenceName(), start, stop));
       current = stop + 1;
     }
   }
   Collections.sort(nonOverlappingExomeIntervals, IntervalUtils.LEXICOGRAPHICAL_ORDER_COMPARATOR);
   exonDB = new HashedListTargetCollection<>(nonOverlappingExomeIntervals);
 }
Example #21
0
  public Object down(Message msg) {
    Address dest = msg.getDest();
    boolean multicast = dest == null;

    if (msg.getSrc() == null) msg.setSrc(localAddress());

    if (discard_all) {
      if (dest == null || dest.equals(localAddress())) loopback(msg);
      return null;
    }

    if (!multicast && drop_down_unicasts > 0) {
      drop_down_unicasts = Math.max(0, drop_down_unicasts - 1);
      return null;
    }

    if (multicast && drop_down_multicasts > 0) {
      drop_down_multicasts = Math.max(0, drop_down_multicasts - 1);
      return null;
    }

    if (down > 0) {
      double r = Math.random();
      if (r < down) {
        if (excludeItself && dest != null && dest.equals(localAddress())) {
          if (log.isTraceEnabled()) log.trace("excluding itself");
        } else {
          log.trace("dropping message");
          num_down++;
          return null;
        }
      }
    }
    return down_prot.down(msg);
  }
Example #22
0
  /** ensure that non-Manual components of flow_tuple have equal dataRanges symmetric about 0.0 */
  public static void equalizeFlow(Vector mapVector, DisplayTupleType flow_tuple)
      throws VisADException, RemoteException {
    double[] range = new double[2];
    double low = Double.MAX_VALUE;
    double hi = -Double.MAX_VALUE;
    boolean anyAuto = false;

    Enumeration maps = mapVector.elements();
    while (maps.hasMoreElements()) {
      ScalarMap map = ((ScalarMap) maps.nextElement());
      DisplayRealType dtype = map.getDisplayScalar();
      DisplayTupleType tuple = dtype.getTuple();
      if (flow_tuple.equals(tuple) && !map.isManual && !map.badRange()) {
        anyAuto = true;
        low = Math.min(low, map.dataRange[0]);
        hi = Math.max(hi, map.dataRange[1]);
      }
    }
    if (!anyAuto) return;
    hi = Math.max(hi, -low);
    low = -hi;
    maps = mapVector.elements();
    while (maps.hasMoreElements()) {
      ScalarMap map = ((ScalarMap) maps.nextElement());
      DisplayRealType dtype = map.getDisplayScalar();
      DisplayTupleType tuple = dtype.getTuple();
      if (flow_tuple.equals(tuple) && !map.isManual && !map.badRange()) {
        map.setRange(null, low, hi, false);
      }
    }
  }
Example #23
0
  void run() {
    InputReader in = new InputReader(System.in);
    PrintWriter out = new PrintWriter(System.out);

    int n = in.nextInt(), q = in.nextInt();
    int[] v = new int[n], c = new int[n];
    for (int i = 0; i < n; ++i) v[i] = in.nextInt();
    for (int i = 0; i < n; ++i) c[i] = in.nextInt();

    for (int i = 0; i < q; ++i) {
      int a = in.nextInt(), b = in.nextInt();
      long[] dp = new long[n + 1];
      Node[] heap = new Node[2];
      Arrays.fill(dp, -INF);
      for (int j = 0; j < 2; ++j) heap[j] = new Node(-INF, -1);
      for (int j = 0; j < n; ++j) {
        long val = v[j], maxv = val * b;
        int color = c[j];
        maxv = Math.max(dp[color] + val * a, maxv);
        maxv = Math.max(choose(heap, color) + val * b, maxv);
        dp[color] = Math.max(maxv, dp[color]);
        update(heap, dp[color], color);
      }

      long ret = 0;
      for (int j = 1; j <= n; ++j) ret = Math.max(ret, dp[j]);
      out.println(ret);
    }

    out.close();
  }
  /**
   * Computes an allele biased version of the allele counts for a given pileup
   *
   * @param alleleCounts the allele counts for the original pileup
   * @param numReadsToRemove number of total reads to remove per allele
   * @return non-null array of new counts needed per allele
   */
  protected static int[] runSmartDownsampling(
      final int[] alleleCounts, final int numReadsToRemove) {
    final int numAlleles = alleleCounts.length;

    int maxScore = scoreAlleleCounts(alleleCounts);
    int[] alleleCountsOfMax = alleleCounts;

    final int numReadsToRemovePerAllele = numReadsToRemove / 2;

    for (int i = 0; i < numAlleles; i++) {
      for (int j = i; j < numAlleles; j++) {
        final int[] newCounts = alleleCounts.clone();

        // split these cases so we don't lose on the floor (since we divided by 2)
        if (i == j) {
          newCounts[i] = Math.max(0, newCounts[i] - numReadsToRemove);
        } else {
          newCounts[i] = Math.max(0, newCounts[i] - numReadsToRemovePerAllele);
          newCounts[j] = Math.max(0, newCounts[j] - numReadsToRemovePerAllele);
        }

        final int score = scoreAlleleCounts(newCounts);

        if (score < maxScore) {
          maxScore = score;
          alleleCountsOfMax = newCounts;
        }
      }
    }

    return alleleCountsOfMax;
  }
Example #25
0
  public static void main(String[] args) throws IOException {
    input.init(System.in);
    PrintWriter out = new PrintWriter(System.out);

    int depth = input.nextInt();
    int n = (1 << (depth + 1));
    int[] as = new int[n];
    for (int i = 2; i < n; i++) as[i] = input.nextInt();
    int[] paths = new int[n];
    int max = 0;
    ArrayList<Integer>[] under = new ArrayList[n];
    for (int i = 0; i < n; i++) under[i] = new ArrayList<Integer>();
    for (int i = (1 << (depth)); i < n; i++) {
      int cur = i;
      while (cur > 1) {
        under[cur].add(i);
        paths[i] += as[cur];
        cur /= 2;
      }
      max = Math.max(max, paths[i]);
    }
    int res = 0;
    for (int i = 2; i < n; i++) {
      int cm = 0;
      for (int x : under[i]) cm = Math.max(cm, paths[x]);
      int diff = max - cm;
      res += diff;
      for (int x : under[i]) paths[x] += diff;
    }
    out.println(res);
    out.close();
  }
  /** get the profiling results for "name" from this database. */
  public ProfilerResults(ProfilerDB db, String name) {
    this.name = name;
    this.db = db;

    // XXX: if "name" is non existing, an empty data will be created
    ProfiledData data = db.getDataset(name);

    this.count = data.getSize();
    this.memories = data.memories;
    this.ids = data.ids;
    this.times = data.times;

    this.current = -1;

    // calc min/max:
    min_times = Integer.MAX_VALUE;
    max_times = Integer.MIN_VALUE;
    min_mems = Long.MAX_VALUE;
    max_mems = Long.MIN_VALUE;

    for (int i = 0; i < count; i++) {
      min_mems = Math.min(min_mems, memories[i]);
      max_mems = Math.max(max_mems, memories[i]);
      min_times = Math.min(min_times, times[i]);
      max_times = Math.max(max_times, times[i]);
    }
  }
Example #27
0
 /**
  * Gets the maximum extent of this envelope across all three dimensions.
  *
  * @return the maximum extent of this envelope
  */
 @Override
 public double maxExtent() {
   if (isNull()) {
     return 0.0;
   }
   return Math.max(getWidth(), Math.max(getHeight(), getDepth()));
 }
 public ReRankCollector(
     int reRankDocs,
     int length,
     Query reRankQuery,
     double reRankWeight,
     SolrIndexSearcher.QueryCommand cmd,
     IndexSearcher searcher,
     Map<BytesRef, Integer> boostedPriority,
     boolean scale)
     throws IOException {
   super(null);
   this.reRankQuery = reRankQuery;
   this.reRankDocs = reRankDocs;
   this.length = length;
   this.boostedPriority = boostedPriority;
   this.scale = scale;
   Sort sort = cmd.getSort();
   if (sort == null) {
     this.mainCollector = TopScoreDocCollector.create(Math.max(this.reRankDocs, length), true);
   } else {
     sort = sort.rewrite(searcher);
     this.mainCollector =
         TopFieldCollector.create(
             sort, Math.max(this.reRankDocs, length), false, true, true, true);
   }
   this.searcher = searcher;
   this.reRankWeight = reRankWeight;
 }
Example #29
0
 /*12. 求二叉树中节点的最大距离
     具体分析(http://blog.csdn.net/lalor/article/details/7626678)
     即二叉树中相距最远的两个节点之间的距离。
     递归解法:
     (1)如果二叉树为空,返回0,同时记录左子树和右子树的深度,都为0
     (2)如果二叉树不为空,最大距离要么是左子树中的最大距离,要么是右子树中的最大距离,
     要么是左子树节点中到根节点的最大距离+右子树节点中到根节点的最大距离,
     同时记录左子树和右子树节点中到根节点的最大距离。
 */
 public static int getMaxDistance(TreeNode node, int maxLeft, int maxRight) {
   // maxLeft, 左子树中的节点距离左子树根节点的最远距离
   // maxRight, 右子树中的节点距离左子树根节点的最远距离
   if (node == null) {
     maxLeft = 0;
     maxRight = 0;
     return 0;
   }
   int maxLL = 0, maxLR = 0, maxRL = 0, maxRR = 0;
   int maxDistLeft, maxDistRight;
   if (node.left != null) {
     maxDistLeft = getMaxDistance(node.left, maxLL, maxLR);
     maxLeft = Math.max(maxLL, maxLR) + 1;
   } else {
     maxDistLeft = 0;
     maxLeft = 0;
   }
   if (node.right != null) {
     maxDistRight = getMaxDistance(node.right, maxRL, maxRR);
     maxRight = Math.max(maxRL, maxRR) + 1;
   } else {
     maxDistRight = 0;
     maxRight = 0;
   }
   int result = Math.max(Math.max(maxDistLeft, maxDistRight), maxLeft + maxRight + 1);
   return result;
 }
Example #30
0
 public int count(
     String[] s1000,
     String[] s100,
     String[] s10,
     String[] s1,
     String[] t1000,
     String[] t100,
     String[] t10,
     String[] t1) {
   String S1000 = concate(s1000);
   String S100 = concate(s100);
   String S10 = concate(s10);
   String S1 = concate(s1);
   String T1000 = concate(t1000);
   String T100 = concate(t100);
   String T10 = concate(t10);
   String T1 = concate(t1);
   int n = S1000.length();
   Interval[] intervals = new Interval[n];
   for (int i = 0; i < n; ++i) {
     intervals[i] =
         new Interval(
             Integer.parseInt(
                 S1000.substring(i, i + 1) + S100.charAt(i) + S10.charAt(i) + S1.charAt(i)),
             Integer.parseInt(
                 T1000.substring(i, i + 1) + T100.charAt(i) + T10.charAt(i) + T1.charAt(i)));
   }
   Arrays.sort(intervals);
   int leftmost = Integer.MAX_VALUE;
   int rightmost = Integer.MIN_VALUE;
   for (int i = 0; i < n; ++i) {
     leftmost = Math.min(leftmost, intervals[i].b);
     rightmost = Math.max(rightmost, intervals[i].a);
   }
   int answer = 0;
   for (int i = 0; i < n; ++i) {
     int total = 0;
     int now = leftmost;
     int j = 0;
     while (true) {
       if (intervals[i].a <= now) {
         now = Math.max(now, intervals[i].b);
       }
       if (now >= rightmost) {
         break;
       }
       int best = now;
       while (j < n && intervals[j].a <= now) {
         best = Math.max(best, intervals[j++].b);
       }
       if (best <= now) {
         return -1;
       }
       total++;
       now = best;
     }
     answer += total;
   }
   return answer;
 }