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; }
public BigInteger count(int n) { BigInteger[] prev = new BigInteger[k]; Arrays.fill(prev, BigInteger.ZERO); prev[s] = BigInteger.ONE; while (n-- > 0) { BigInteger[] next = new BigInteger[k]; Arrays.fill(next, BigInteger.ZERO); for (int i = 0; i < k; ++i) { if (prev[i].signum() <= 0) { continue; } for (int j = 0; j < z; ++j) { if (e[j][i] < 0) { continue; } next[e[j][i]] = next[e[j][i]].add(prev[i]); } } prev = next; } BigInteger ans = BigInteger.ZERO; for (int term : t) { ans = ans.add(prev[term]); } return ans; }
@Override public Map<String, Object> saveMap(Map<String, Object> object, Class clazz) throws Exception { StringBuilder sql = new StringBuilder(); EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz); sql.append("INSERT INTO "); sql.append(entityInfo.getTableName()); sql.append("("); List<String> columns = new ArrayList<String>(); List<Object> values = new ArrayList<Object>(); Map<String, String> ptcMap = ClassUtils.propToColumnMap.get(entityInfo.getClazzName()); for (Map.Entry<String, Object> entry : object.entrySet()) { columns.add(ptcMap.get(entry.getKey())); values.add(entry.getValue()); } sql.append(StringUtils.join(columns, ",")); sql.append(") VALUES("); String[] params = new String[values.size()]; Arrays.fill(params, "?"); sql.append(StringUtils.join(params, ",")); sql.append(")"); if (entityInfo.getStrategy().equals(GenerationType.IDENTITY)) { Long id = addReutrnId(sql.toString(), values); if (id != null) { object.put(entityInfo.getPkName(), id); } } else { add(sql.toString(), values); } return object; }
public static void main(String[] args) { while (true) { int X = stdin.nextInt(), Y = stdin.nextInt(); if ((X | Y) == 0) break; int[][] map = new int[Y + 1][X + 2], DP = new int[Y + 1][X + 2]; Arrays.fill(map[0], UNSAFE); Arrays.fill(DP[0], 0); for (int i = 1; i <= Y; ++i) { for (int j = 1; j <= X; ++j) { map[i][j] = stdin.nextInt(); DP[i][j] = i == 1 && map[i][j] == SAFE ? 1 : 0; } map[i][0] = map[i][X + 1] = DP[i][0] = map[i][X + 1] = 0; // UNSAFE } for (int y = 2; y <= Y; ++y) { for (int x = 1; x <= X; ++x) { if (map[y][x] == SAFE) { for (int k = 0; k < 3; ++k) if (map[y - dy[k]][x - dx[k]] == SAFE) DP[y][x] += DP[y - dy[k]][x - dx[k]]; if (map[y - 2][x] == JUMP) DP[y][x] += DP[y - 2][x]; } if (map[y][x] == JUMP) { if (map[y - 1][x] == SAFE) DP[y][x] += DP[y - 1][x]; if (map[y - 2][x] == JUMP) DP[y][x] += DP[y - 2][x]; } } } int ans = 0; for (int j = 1; j <= X; ++j) { ans += DP[Y][j]; if (map[Y - 1][j] == JUMP) ans += DP[Y - 1][j]; } System.out.println(ans); } }
// [algo] hungary BipartiteMaximumMatching // [module] hungary public static int hungary(int nu, int nv, int[][] e, int[] mu, int[] mv) { Arrays.fill(mu, -1); Arrays.fill(mv, -1); int[] q = new int[nu]; int[] p = new int[nv]; int ret = 0; for (int i = 0; i < nu; ++i) { Arrays.fill(p, -1); q[0] = i; BFS: for (int begin = 0, end = 1; begin < end; ++begin) { int u = q[begin]; for (int v : e[u]) { if (p[v] == -1) { p[v] = u; if (mv[v] == -1) { int t = v; while (t != -1) { u = p[t]; v = t; t = mu[u]; mu[u] = v; mv[v] = u; } ++ret; break BFS; } else { q[end++] = mv[v]; } } } } } return ret; }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int cases = 1; while (true) { st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); if (n == 0 && m == 0) break; a = new int[n]; b = new int[m]; dp = new int[n + 1][m + 1]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); Arrays.fill(dp[i], -1); } Arrays.fill(dp[n], -1); st = new StringTokenizer(in.readLine()); for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken()); System.out.println("Twin Towers #" + cases); System.out.println("Number of Tiles : " + LCS(0, 0)); System.out.println(); cases++; } in.close(); System.exit(0); }
static double[] similarity(LatentDirichletAllocation lda0, LatentDirichletAllocation lda1) { int numTopics = lda0.numTopics(); int numPairs = numTopics * (numTopics - 1); @SuppressWarnings({"unchecked", "rawtypes"}) // ok given use w. erasure ScoredObject<int[]>[] pairs = (ScoredObject<int[]>[]) new ScoredObject[numPairs]; int pos = 0; for (int i = 0; i < numTopics; ++i) { for (int j = 0; j < numTopics; ++j) { if (i == j) continue; double divergence = Statistics.symmetrizedKlDivergence( lda0.wordProbabilities(i), lda1.wordProbabilities(j)); pairs[pos++] = new ScoredObject<int[]>(new int[] {i, j}, divergence); } } Arrays.sort(pairs, ScoredObject.comparator()); boolean[] taken0 = new boolean[numTopics]; Arrays.fill(taken0, false); boolean[] taken1 = new boolean[numTopics]; Arrays.fill(taken1, false); double[] scores = new double[numTopics]; int scorePos = 0; for (pos = 0; pos < numPairs && scorePos < numTopics; ++pos) { int[] pair = pairs[pos].getObject(); if (!taken0[pair[0]] && !taken1[pair[1]]) { taken0[pair[0]] = true; taken1[pair[1]] = true; scores[scorePos++] = pairs[pos].score(); } } return scores; }
public boolean isValidSudoku(char[][] board) { boolean[] used = new boolean[9]; for (int i = 0; i < 9; i++) { Arrays.fill(used, false); for (int j = 0; j < 9; j++) { if (check(board[i][j], used) == false) return false; } Arrays.fill(used, false); for (int j = 0; j < 9; j++) { if (check(board[j][i], used) == false) return false; } } for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) { Arrays.fill(used, false); for (int i = r * 3; i < r * 3 + 3; i++) { for (int j = c * 3; j < c * 3 + 3; j++) { if (check(board[i][j], used) == false) return false; } } } } return true; }
int Query() { int minimum = 100001; visited = new boolean[V]; Arrays.fill(visited, false); depth = new int[V]; Arrays.fill(depth, -1); low = new int[V]; Arrays.fill(low, -1); parent = new int[V]; Arrays.fill(parent, -1); articulationPoints = new TreeMap<Integer, Boolean>(); getArticulationPoints(0, 0); for (Map.Entry<Integer, Boolean> entry : articulationPoints.entrySet()) { int i = (int) entry.getKey(); if (RatingScore[i] < minimum) { minimum = RatingScore[i]; } } return minimum != 100001 ? minimum : -1; }
public static void main(String[] args) { int size = 6; // Or get the size from the command line: if (args.length != 0) size = Integer.parseInt(args[0]); boolean[] a1 = new boolean[size]; byte[] a2 = new byte[size]; char[] a3 = new char[size]; short[] a4 = new short[size]; int[] a5 = new int[size]; long[] a6 = new long[size]; float[] a7 = new float[size]; double[] a8 = new double[size]; String[] a9 = new String[size]; Arrays.fill(a1, true); Arrays2.print("a1 = ", a1); Arrays.fill(a2, (byte) 11); Arrays2.print("a2 = ", a2); Arrays.fill(a3, 'x'); Arrays2.print("a3 = ", a3); Arrays.fill(a4, (short) 17); Arrays2.print("a4 = ", a4); Arrays.fill(a5, 19); Arrays2.print("a5 = ", a5); Arrays.fill(a6, 23); Arrays2.print("a6 = ", a6); Arrays.fill(a7, 29); Arrays2.print("a7 = ", a7); Arrays.fill(a8, 47); Arrays2.print("a8 = ", a8); Arrays.fill(a9, "Hello"); Arrays2.print("a9 = ", a9); // Manipulating ranges: Arrays.fill(a9, 3, 5, "World"); Arrays2.print("a9 = ", a9); }
public void clearCounts() { if (foundCorrect != null) { foundCorrect.clear(); } else { foundCorrect = new IntCounter<L>(); } if (foundGuessed != null) { foundGuessed.clear(); } else { foundGuessed = new IntCounter<L>(); } if (correctGuesses != null) { correctGuesses.clear(); } else { correctGuesses = new IntCounter<L>(); } if (tpCount != null) { Arrays.fill(tpCount, 0); } if (fnCount != null) { Arrays.fill(fnCount, 0); } if (fpCount != null) { Arrays.fill(fpCount, 0); } tokensCount = 0; tokensCorrect = 0; }
public int minimalPlanets(int[] A, int[] B) { this.A = A.length > B.length ? A : B; this.B = A.length > B.length ? B : A; int[][] memo = new int[this.A.length][this.B.length]; for (int[] m : memo) { Arrays.fill(m, -1); } int best = find(memo, 0, 0, 1, 1); for (int i = 0; i < this.A.length; i++) { for (int j = 0; j < this.B.length; j++) { if (this.A[i] != this.B[j]) { memo = new int[this.A.length][this.B.length]; for (int[] m : memo) { Arrays.fill(m, -1); } best = Math.max(best, find(memo, 0, 0, this.B[j], this.A[i])); } } } return A.length + (B.length - best); }
public static int[] getLis(int[] x) { int n = x.length; int[] len = new int[n]; Arrays.fill(len, 1); int[] pred = new int[n]; Arrays.fill(pred, -1); for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (x[j] < x[i] && len[i] < len[j] + 1) { len[i] = len[j] + 1; pred[i] = j; } } } int bi = 0; for (int i = 1; i < n; i++) { if (len[bi] < len[i]) { bi = i; } } int cnt = len[bi]; int[] res = new int[cnt]; for (int i = bi; i != -1; i = pred[i]) { res[--cnt] = x[i]; } return res; }
public void clear() { super.clear(); final int[] keys = this._set; final Object[] vals = this._values; final byte[] states = this._states; Arrays.fill(this._set, 0, this._set.length, 0); Arrays.fill(this._values, 0, this._values.length, null); Arrays.fill(this._states, 0, this._states.length, (byte) 0); }
/** * Creates a partial mapping. * * <p>Initially, no element is mapped to any other: * * <table border="1"> * <caption>Example</caption> * <tr> * <th>source</th> * <td>0</td> * <td>1</td> * <td>2</td> * </tr> * <tr> * <th>target</th> * <td>-1</td> * <td>-1</td> * <td>-1</td> * </tr> * </table> * * <table border="1"> * <caption>Example</caption> * <tr> * <th>target</th> * <td>0</td> * <td>1</td> * <td>2</td> * <td>3</td> * </tr> * <tr> * <th>source</th> * <td>-1</td> * <td>-1</td> * <td>-1</td> * <td>-1</td> * </tr> * </table> * * @param sourceCount Number of source elements * @param targetCount Number of target elements * @param mappingType Mapping type; must not allow multiple sources per target or multiple * targets per source */ public PartialMapping(int sourceCount, int targetCount, MappingType mappingType) { this.mappingType = mappingType; assert mappingType.isSingleSource() : mappingType; assert mappingType.isSingleTarget() : mappingType; this.sources = new int[targetCount]; this.targets = new int[sourceCount]; Arrays.fill(sources, -1); Arrays.fill(targets, -1); }
@Test public void large_record_update() { byte[] b = new byte[100000]; Arrays.fill(b, (byte) 111); long recid = engine.recordPut(b, Serializer.BYTE_ARRAY_SERIALIZER); Arrays.fill(b, (byte) 222); engine.recordUpdate(recid, b, Serializer.BYTE_ARRAY_SERIALIZER); byte[] b2 = engine.recordGet(recid, Serializer.BYTE_ARRAY_SERIALIZER); assertArrayEquals(b, b2); }
public Cedars(String args[]) throws ArchiveException, IOException, HoneycombTestException { verbose = false; parseArgs(args); initHCClient(host); // generate lists of random sizes around 30M and 3M // sort ascending to allow continuous expansion try { initRandom(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } sizes = new long[n_files]; for (int i = 0; i < sizes.length; i++) { sizes[i] = MIN_SIZE + (long) (rand.nextDouble() * (double) RANGE); } Arrays.sort(sizes); sizes2 = new long[n_files]; for (int i = 0; i < sizes2.length; i++) { sizes2[i] = MIN_SIZE2 + (long) (rand.nextDouble() * (double) RANGE2); } Arrays.sort(sizes2); sizes3 = new long[n_files]; for (int i = 0; i < sizes3.length; i++) { sizes3[i] = MIN_SIZE3 + (long) (rand.nextDouble() * (double) RANGE3); } Arrays.sort(sizes3); oids = new String[n_files]; Arrays.fill(oids, null); shas = new String[n_files]; Arrays.fill(shas, null); if (out_file != null) { try { String host = clnthost; fo = new FileWriter(out_file, true); // append=true flog("#S Cedars [" + host + "] " + new Date() + "\n"); } catch (Exception e) { System.err.println("Opening " + out_file); e.printStackTrace(); System.exit(1); } } Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown(), "Shutdown")); doIt(); done = true; }
/** Calculates the matrix of all shortest paths, but does not populate the paths map. */ private void lazyCalculateMatrix() { if (d != null) { // already done return; } int n = vertices.size(); // init the backtrace matrix backtrace = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(backtrace[i], -1); } // initialize matrix, 0 d = new double[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(d[i], Double.POSITIVE_INFINITY); } // initialize matrix, 1 for (int i = 0; i < n; i++) { d[i][i] = 0.0; } // initialize matrix, 2 Set<E> edges = graph.edgeSet(); for (E edge : edges) { V v1 = graph.getEdgeSource(edge); V v2 = graph.getEdgeTarget(edge); int v_1 = vertices.indexOf(v1); int v_2 = vertices.indexOf(v2); d[v_1][v_2] = graph.getEdgeWeight(edge); if (!(graph instanceof DirectedGraph<?, ?>)) { d[v_2][v_1] = graph.getEdgeWeight(edge); } } // run fw alg for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double ik_kj = d[i][k] + d[k][j]; if (ik_kj < d[i][j]) { d[i][j] = ik_kj; backtrace[i][j] = k; } } } } }
public SegmentTreeFast2(int n) { value = new int[2 * n]; for (int i = 0; i < n; i++) value[i + n] = getInitValue(); for (int i = 2 * n - 1; i > 1; i -= 2) value[i >> 1] = queryOperation(value[i], value[i ^ 1]); delta = new int[2 * n]; Arrays.fill(delta, getNeutralDelta()); len = new int[2 * n]; Arrays.fill(len, n, 2 * n, 1); for (int i = 2 * n - 1; i > 1; i -= 2) len[i >> 1] = len[i] + len[i ^ 1]; }
public long numWays(int width, int height, String[] bad) { dpTable = new long[width][height]; final boolean valid[][] = new boolean[width][height]; for (int i = 0; i < width; ++i) { Arrays.fill(dpTable[i], -1l); Arrays.fill(valid[i], true); } dpTable[0][0] = 0l; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) {} } return 0l; }
private Haplotype getHaplotypeFromRead( final PileupElement p, final int contextSize, final int locus) { final GATKSAMRecord read = p.getRead(); int readOffsetFromPileup = p.getOffset(); final byte[] haplotypeBases = new byte[contextSize]; Arrays.fill(haplotypeBases, (byte) REGEXP_WILDCARD); final double[] baseQualities = new double[contextSize]; Arrays.fill(baseQualities, 0.0); byte[] readBases = read.getReadBases(); readBases = AlignmentUtils.readToAlignmentByteArray( read.getCigar(), readBases); // Adjust the read bases based on the Cigar string byte[] readQuals = read.getBaseQualities(); readQuals = AlignmentUtils.readToAlignmentByteArray( read.getCigar(), readQuals); // Shift the location of the qual scores based on the Cigar string readOffsetFromPileup = AlignmentUtils.calcAlignmentByteArrayOffset( read.getCigar(), p, read.getAlignmentStart(), locus); final int baseOffsetStart = readOffsetFromPileup - (contextSize - 1) / 2; for (int i = 0; i < contextSize; i++) { final int baseOffset = i + baseOffsetStart; if (baseOffset < 0) { continue; } if (baseOffset >= readBases.length) { break; } if (readQuals[baseOffset] == PileupElement.DELETION_BASE) { readQuals[baseOffset] = PileupElement.DELETION_QUAL; } if (!BaseUtils.isRegularBase(readBases[baseOffset])) { readBases[baseOffset] = (byte) REGEXP_WILDCARD; readQuals[baseOffset] = (byte) 0; } // N's shouldn't be treated as distinct bases readQuals[baseOffset] = (byte) Math.min((int) readQuals[baseOffset], p.getMappingQual()); if (((int) readQuals[baseOffset]) < 5) { readQuals[baseOffset] = (byte) 0; } // quals less than 5 are used as codes and don't have actual probabilistic meaning behind // them haplotypeBases[i] = readBases[baseOffset]; baseQualities[i] = (double) readQuals[baseOffset]; } return new Haplotype(haplotypeBases, baseQualities); }
private static void processCallerMethod( JavaChangeInfo changeInfo, PsiMethod caller, PsiMethod baseMethod, boolean toInsertParams, boolean toInsertThrows) throws IncorrectOperationException { LOG.assertTrue(toInsertParams || toInsertThrows); if (toInsertParams) { List<PsiParameter> newParameters = new ArrayList<PsiParameter>(); ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters()); final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters(); PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod); for (JavaParameterInfo info : primaryNewParms) { if (info.getOldIndex() < 0) newParameters.add(createNewParameter(changeInfo, info, substitutor)); } PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm); } if (toInsertThrows) { List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>(); final PsiReferenceList throwsList = caller.getThrowsList(); ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements()); final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions(); for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) { if (thrownExceptionInfo.getOldIndex() < 0) { final PsiClassType type = (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager()); final PsiJavaCodeReferenceElement ref = JavaPsiFacade.getInstance(caller.getProject()) .getElementFactory() .createReferenceElementByType(type); newThrowns.add(ref); } } PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); ChangeSignatureUtil.synchronizeList( throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm); } }
void solve() throws IOException { in("knights.in"); out("knights.out"); int n = readInt(); char[][] f = new char[n][n]; for (int i = 0; i < n; ++i) { f[i] = readLine().toCharArray(); } int m = n * n; l = new int[m][8]; for (int i = 0; i < m; ++i) { Arrays.fill(l[i], -1); } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (((i + j) & 1) == 0 && f[i][j] == '.') { for (int k = 0; k < 8; ++k) { int ii = i + di[k]; int jj = j + dj[k]; if (ii >= 0 && ii < n && jj >= 0 && jj < n && f[ii][jj] == '.') { l[i * n + j][k] = ii * n + jj; } } } } } p = new int[m]; mask = new boolean[m]; Arrays.fill(p, -1); for (int i = 0; i < m; ++i) { Arrays.fill(mask, true); can(i); } for (int i = 0; i < m; ++i) { if (p[i] != -1) { f[i / n][i % n] = 'K'; } } for (int i = 0; i < n; ++i) { println(String.valueOf(f[i])); } exit(); }
@Test public void large_record_delete() { byte[] b = new byte[100000]; Arrays.fill(b, (byte) 111); long recid = engine.recordPut(b, Serializer.BYTE_ARRAY_SERIALIZER); engine.recordDelete(recid); }
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(); } }
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(); }
/** * Move the cursor <i>where</i> characters, withough checking the current buffer. * * @see #where * @param where the number of characters to move to the right or left. */ private final void moveInternal(final int where) throws IOException { // debug ("move cursor " + where + " (" // + buf.cursor + " => " + (buf.cursor + where) + ")"); buf.cursor += where; char c; if (where < 0) { int len = 0; for (int i = buf.cursor; i < buf.cursor - where; i++) { if (buf.getBuffer().charAt(i) == '\t') len += TAB_WIDTH; else len++; } char cbuf[] = new char[len]; Arrays.fill(cbuf, BACKSPACE); out.write(cbuf); return; } else if (buf.cursor == 0) { return; } else if (mask != null) { c = mask.charValue(); } else { printCharacters(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray()); return; } // null character mask: don't output anything if (NULL_MASK.equals(mask)) { return; } printCharacters(c, Math.abs(where)); }
public void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); graph = new ArrayList[n + 1]; color = new int[n + 1]; Arrays.fill(color, 0); for (int i = 0; i < m; i++) { int from = in.nextInt(); int to = in.nextInt(); if (graph[from] == null) { graph[from] = new ArrayList<Integer>(); } graph[from].add(to); } topSort(); if (hasCycle) { out.print(-1); return; } for (Integer anAnswer : answer) { out.printf("%d ", anAnswer); } }
public static int[] calculateVectorSpace(BufferedImage image) { clusters = createClusters(image); int[] vectorSpace = new int[IMAGE_WIDTH * IMAGE_HEIGHT]; Arrays.fill(vectorSpace, -1); boolean refineNeeded = true; int loops = 0; while (refineNeeded) { refineNeeded = false; loops++; for (int y = 0; y < IMAGE_HEIGHT; y++) { for (int x = 0; x < IMAGE_WIDTH; x++) { int pixel = image.getRGB(x, y); Cluster cluster = getMinCluster(pixel); if (vectorSpace[IMAGE_WIDTH * y + x] != cluster.getId()) { if (vectorSpace[IMAGE_WIDTH * y + x] != -1) { clusters[vectorSpace[IMAGE_WIDTH * y + x]].removePixel(pixel); } cluster.addPixel(pixel); refineNeeded = true; vectorSpace[IMAGE_WIDTH * y + x] = cluster.getId(); } } } } System.out.println("Took " + loops + " loops."); return vectorSpace; }
/** * Convert a single Tree[String] to Tree[StateSet] * * @param tree * @param numStates * @param tagNumberer * @return */ public static short[] initializeSubStateArray( List<Tree<String>> trainTrees, List<Tree<String>> validationTrees, Numberer tagNumberer, short nSubStates) { // boolean dontSplitTags) { // first generate unsplit grammar and lexicon short[] nSub = new short[2]; nSub[0] = 1; nSub[1] = nSubStates; // do the validation set so that the numberer sees all tags and we can // allocate big enough arrays // note: although this variable is never read, this constructor adds the // validation trees into the tagNumberer as a side effect, which is // important StateSetTreeList trainStateSetTrees = new StateSetTreeList(trainTrees, nSub, true, tagNumberer); @SuppressWarnings("unused") StateSetTreeList validationStateSetTrees = new StateSetTreeList(validationTrees, nSub, true, tagNumberer); StateSetTreeList.initializeTagNumberer(trainTrees, tagNumberer); StateSetTreeList.initializeTagNumberer(validationTrees, tagNumberer); short numStates = (short) tagNumberer.total(); short[] nSubStateArray = new short[numStates]; short two = nSubStates; Arrays.fill(nSubStateArray, two); // System.out.println("Everything is split in two except for the root."); nSubStateArray[0] = 1; // that's the ROOT return nSubStateArray; }