src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
/** * Created by IntelliJ IDEA. * User: Nick * Date: 08.08.2010 * Time: 20:44:02 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; import java.util.regex.*; public class B { public static void main(String[] args) { Scanner input = new Scanner (System.in); Pattern rc_style = Pattern.compile("R[0-9]+C[0-9]+"); int n = input.nextInt(); while(n-- > 0) { String str = input.next(); Matcher m = rc_style.matcher(str); if (m.matches()) { String nums[] = str.split("[RC]"); String row = nums[1]; String col = nums[2]; String buffer = ""; int col_num = Integer.valueOf(col); while(col_num > 0) { if (col_num % 26 > 0) { buffer += (char)(col_num % 26 + 'A' - 1); col_num /= 26; } else { buffer += 'Z'; col_num /= 26; col_num--; } } for (int i = buffer.length() - 1; i >= 0; --i) { System.out.print(buffer.charAt(i)); } System.out.println(row); } else { String col = str.split("[0-9]+")[0]; String row = str.split("[A-Z]+")[1]; int col_num = 0; int shift = 1; for (int i = col.length() - 1; i >= 0; --i){ col_num += (int)(col.charAt(i) - 'A' + 1) * shift; shift *= 26; } System.out.println("R" + row + "C" + col_num); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import java.util.regex.*; public class Main implements Runnable { StreamTokenizer ST; PrintWriter out; BufferedReader br; int inf = 1000000000; int nextInt() throws IOException{ ST.nextToken(); return (int)ST.nval; } long nextLong() throws IOException{ ST.nextToken(); return (long)ST.nval; } String next() throws IOException{ ST.nextToken(); return ST.sval; } double nextD() throws IOException{ ST.nextToken(); return ST.nval; } public static void main(String[] args) throws IOException { new Thread(new Main()).start(); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1")); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); ST = new StreamTokenizer(br); solve(); out.close(); br.close(); } catch (IOException e) { throw new IllegalStateException(e); } } String code(int x) { x--; StringBuilder sb = new StringBuilder(); while (x>0) { int c = x%26; if (x<10) sb.append((char)(c+'0')); else sb.append((char)('A'+c-10)); x /= 26; } if (sb.length()==0) sb.append("0"); return sb.toString(); } StringBuilder sb = new StringBuilder(); public void solve() throws IOException { int tt = Integer.parseInt(br.readLine()); HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i=1; i<=10; i++) map.put(code(i), i); while (tt-->0) { String s = br.readLine(); if (s.matches("^[A-Z]+[0-9]+$")) { int t = 0; while (Character.isLetter(s.charAt(t))) t++; int r = Integer.parseInt(s.substring(t)); s = s.substring(0, t); int res = 0; for (int c:s.toCharArray()) { res *= 26; res += c-'A'+1; } out.println("R"+r+"C"+res); } else { int t = s.indexOf('C'); int c = Integer.parseInt(s.substring(1, t)); int r = Integer.parseInt(s.substring(t+1)); //out.println(r+" "+c); sb.setLength(0); while (r>0) { r--; int ch = r%26; sb.append((char)('A'+ch)); r /= 26; } sb = sb.reverse(); out.println(sb+""+c); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class B { private Scanner in; private PrintWriter out; public void solve() { String str = in.next(); List<String> sp = new ArrayList<String>(); StringBuilder sb = null; int kind = -1; for(int i = 0;i < str.length();i++){ char c = str.charAt(i); if(c >= 'A' && c <= 'Z' && kind != 0){ if(sb != null){ sp.add(sb.toString()); } sb = new StringBuilder(); kind = 0; } if(c >= '0' && c <= '9' && kind != 1){ if(sb != null){ sp.add(sb.toString()); } sb = new StringBuilder(); kind = 1; } sb.append(c); } sp.add(sb.toString()); if(sp.size() == 2){ // BC23 String bc = sp.get(0); int v = 0; for(int i = 0;i < bc.length();i++){ v = 26 * v + (bc.charAt(i) - 'A' + 1); } out.println("R" + sp.get(1) + "C" + Integer.toString(v)); }else{ // R23C55 int v = Integer.parseInt(sp.get(3)); StringBuilder sbb = new StringBuilder(); for(;v > 0;v/=26){ v--; sbb.append((char)((v % 26) + 'A')); } sbb.reverse(); out.println(sbb.toString() + sp.get(1)); } out.flush(); } public void run() throws Exception { // in = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")))); // out = new PrintWriter(new FileWriter(new File("output.txt"))); // in = new Scanner(new StringReader("2\nR23C55\nR26C26\nZ26")); in = new Scanner(System.in); // System.setOut(new PrintStream(new BufferedOutputStream(System.out))); out = new PrintWriter(System.out); int n = in.nextInt(); // int n = 1; for(int i = 1;i <= n;i++){ long t = System.currentTimeMillis(); solve(); // System.err.printf("%04d/%04d %7d%n", i, n, System.currentTimeMillis() - t); } } public static void main(String[] args) throws Exception { new B().run(); } private int ni() { return Integer.parseInt(in.next()); } private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); } private void tra(int[] a) {System.out.println(Arrays.toString(a));} private void tra(int[][] a) { for(int[] e : a){ System.out.println(Arrays.toString(e)); } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-- >0){ String str = scn.next(); Pattern p = Pattern.compile("R[0-9]+C[0-9]+"); Matcher m = p.matcher(str); if (m.matches()){ String nums[] = str.split("[RC]"); String first = nums[1]; String second = nums[2]; String ans = ""; long num = Integer.parseInt(second); while(num >0){ if (num % 26 > 0){ ans += (char)(num%26+'A'-1); num/=26; } else { ans += 'Z'; num/=26; num--; } } for (int i = ans.length()-1; i>=0;--i){ System.out.print(ans.charAt(i)); } System.out.println(first); } else { String first = str.split("[0-9]+")[0]; String second = str.split("[A-Z]+")[1]; System.out.print("R"+second); long num = 0, pow = 1; for (int i = first.length()-1; i>=0; --i){ num += (long)(first.charAt(i)-'A'+1) * pow; pow*=26; } System.out.println("C"+num); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class b implements Runnable{ PrintWriter out = null; public int toint(String s){ int res = 0; for (int i = 0; i < s.length(); i++){ res *= 10; res += s.charAt(i)-'0'; } return res; } public void tostr(int k){ if (k == 0) return; tostr((k-1)/26); out.print((char)(('A'+((k-1)%26)))); } public int fromstr(String s){ if (s.length() == 0) return 0; int r = s.charAt(s.length()-1)-'A'+1; r += 26*(fromstr(s.substring(0,s.length()-1))); return r; } public void run(){ try{ Scanner in = new Scanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); for (int t = 0; t < n; t++){ int rp = -1; int cp = -1; String s = in.next(); for (int i = 0; i < s.length(); i++) if (s.charAt(i) == 'R') rp = i; else if (s.charAt(i) == 'C') cp = i; boolean good = true; if (rp == 0 && cp > 1){ for (int i = 0; i <= cp; i++) if (s.charAt(i) >= '0' && s.charAt(i) <= '9') good = false; } if (good){ int k = 0; for (;s.charAt(k) < '0' || s.charAt(k) > '9'; k++); int r = toint(s.substring(k,s.length())); int c = fromstr(s.substring(0,k)); out.print('R'); out.print(r); out.print('C'); out.println(c); } else { int r = toint(s.substring(1,cp)); int c = toint(s.substring(cp+1,s.length())); tostr(c); out.println(r); } } in.close(); out.close(); } catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args){ new Thread(new b()).start(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.*; import java.util.regex.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); Pattern rc_style = Pattern.compile("R[0-9]+C[0-9]+"); int n = input.nextInt(); while(n-- > 0) { String str = input.next(); Matcher m = rc_style.matcher(str); if(m.matches()) { String nums[] = str.split("[RC]"); String row = nums[1]; String col = nums[2]; String buffer = ""; int col_num = Integer.valueOf(col); while(col_num > 0) { if(col_num % 26 > 0) { buffer += (char)(col_num % 26 + 'A' - 1); col_num /= 26; } else { buffer += 'Z'; col_num /= 26; col_num--; } } for(int i = buffer.length() - 1; i >= 0; i--) System.out.print(buffer.charAt(i)); System.out.println(row); } else { String col = str.split("[0-9]+")[0]; String row = str.split("[A-Z]+")[1]; int col_num = 0; int shift = 1; for(int i = col.length() - 1; i >= 0; i--) { col_num += (int) (col.charAt(i) - 'A' + 1) * shift; shift *= 26; } System.out.println("R" + row + "C" + col_num); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; public class B { public static String toB(String str){ String row,col; int i=0; while(i<str.length() && str.charAt(i)<='Z'&&str.charAt(i)>='A')i++; col = str.substring(0,i); row = str.substring(i,str.length()); StringBuffer sb = new StringBuffer(col); col = sb.reverse().toString(); int accum = 0; for(i=0;i<col.length();i++){ int val = getValue(col.charAt(i)); accum+=val*Math.pow(26, i); } return "R"+row+"C"+accum; } public static String toA(String str){ int i = str.indexOf('C'); String row,col,ans=""; row = str.substring(1,i); col = str.substring(i+1,str.length()); int colVal = Integer.parseInt(col),mod; while(colVal>0){ mod = colVal%26; if(mod==0){ ans+='Z'; colVal--; } else{ ans+=getLetter(mod); } colVal/=26; } StringBuffer sb = new StringBuffer(ans); ans = sb.reverse().toString(); return ans+row; } public static int getValue(char c){ return c-'A'+1; } public static char getLetter(int n){ return (char)(n+'A'-1); } public static void main(String[] args)throws Exception{ Scanner in = new Scanner(System.in); int cases = in.nextInt(); for(int i = 0;i<cases;i++){ String str = in.next(); if(str.charAt(0)=='R' && str.charAt(1)>='0'&&str.charAt(1)<='9' && str.indexOf('C')!=-1){ System.out.println(toA(str)); } else System.out.println(toB(str)); } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.util.regex.*; public class Main { private static String encode(long rowNum) { if(rowNum<=26) { return String.valueOf((char)('A'+rowNum-1)); } else { if(rowNum%26==0){ return encode((long)Math.floor((double)rowNum/26)-1) + String.valueOf((char)('A'+26-1)); } else { return encode((long)Math.floor((double)rowNum/26)) + String.valueOf((char)('A'+rowNum%26-1)); } } } private static long decode(String rowNum){ long result = 0; char rowChars[] = rowNum.toCharArray(); for(int i=rowChars.length-1;i>=0;i--){ result+= (rowChars[i]-'A'+1) * (long)Math.pow(26,rowChars.length-i-1); } return result; } public static void main(String arg[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); Pattern p1 = Pattern.compile("R\\d+C\\d+"); Pattern p2 = Pattern.compile("\\d+"); for(int i=0;i<t;i++){ String input = in.readLine(); Matcher m1 = p1.matcher(input); Matcher m2 = p2.matcher(input); if(m1.matches()){ String result = ""; if(m2.find()){ result = m2.group(); } if(m2.find()){ result = encode(Long.parseLong(m2.group()))+result; } System.out.println(result); } else { String result = "R"; if(m2.find()){ result += m2.group(); } result += "C"; System.out.println(result+decode(input.replaceAll(m2.group(),""))); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Round1B { public static void main(String[] args) throws Exception { new Round1B().run(); } private void run() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine().trim()); while (tc > 0) { String s = br.readLine().trim(); if (s.matches("R[0-9]+C[0-9]+")) { Pattern p = Pattern.compile("R([0-9]+)C([0-9]+)"); Matcher m = p.matcher(s); if (m.matches()) { int rows = Integer.parseInt(m.group(1)); int cols = Integer.parseInt(m.group(2)); String col = ""; while (cols > 0) { int mod = (cols - 1) % 26; col = (char)('A' + mod) + col; cols = (cols - 1) / 26; } System.out.println(col + rows); } else { throw new Exception(); } } else { Pattern p = Pattern.compile("([A-Z]+)([0-9]+)"); Matcher m = p.matcher(s); if (m.matches()) { int rows = Integer.parseInt(m.group(2)); int cols = 0; int mul = 1; for (int i = m.group(1).length() - 1; i >= 0; i--) { cols += mul * (m.group(1).charAt(i) - 'A' + 1); mul *= 26; } System.out.printf("R%dC%d\n", rows, cols); } else { throw new Exception(); } } tc--; } br.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.PrintWriter; import java.util.*; /* 10 R1C1 A1 R1C26 Z1 R1C27 AA1 R1C28 AB1 R1C52 AZ1 */ public class Main { Scanner in; PrintWriter out; boolean isFirst(String line){ int pos = 0; while( pos<line.length() && Character.isLetter(line.charAt(pos))){ pos++; } while( pos<line.length() && Character.isDigit(line.charAt(pos))){ pos++; } return pos!=line.length(); } void solve() { int n = in.nextInt(); in.nextLine(); for (int i = 1; i<=n; i++){ String line = in.nextLine(); line = line.toUpperCase(); if (isFirst(line)){ int pos = 1; long row = 0; while(Character.isDigit(line.charAt(pos))){ row*=10; row+=line.charAt(pos)-'0'; pos++; } pos++; long col = 0; while(pos<line.length() && Character.isDigit(line.charAt(pos))){ col*=10; col+=line.charAt(pos)-'0'; pos++; } StringBuilder sb = new StringBuilder(); while(col>0){ sb.append((char)('A'+((col-1)%26))); col--; col/=26; } sb = sb.reverse(); out.print(sb); out.println(row); // ��������� � 1 ������� }else{ // ��������� �� 2 ������� int pos = 0; long col = 0; while( pos<line.length() && Character.isLetter(line.charAt(pos))){ col*=26; col+=line.charAt(pos)-'A'+1; pos++; } long row = 0; while(pos<line.length() && Character.isDigit(line.charAt(pos))){ row*=10; row+=line.charAt(pos)-'0'; pos++; } out.println("R"+row+"C"+col); } } } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.FileNotFoundException; import java.util.Scanner; /** * Date: 19.02.2010 * Time: 14:56:28 * * @author Sergey Bankevich ([email protected]) */ public class B1 { static Scanner in; public static void main( String[] args ) throws FileNotFoundException { in = new Scanner( System.in ); int tn = in.nextInt(); for ( int i = 0; i < tn; i ++ ) { String s = in.next(); /*for ( int i = 1; i <= 100; i ++ ) { for ( int j = 1; j <= 100; j ++ ) { String s = "R" + i + "C" + j; for ( char j = 'A'; j <= 'Z'; j ++ ) { String s = j + "" + i; System.out.println( s );*/ char[] c = s.toCharArray(); boolean second = true; second &= c[0] == 'R'; int r = s.indexOf( "C" ); if ( r > 0 ) { second &= isNumber( s.substring( 1, r ) ) && isNumber( s.substring( r + 1 ) ); } else { second = false; } if ( second ) { System.out.println( toLetters( s.substring( r + 1 ) ) + s.substring( 1, r ) ); } else { r = 0; while ( c[r] >= 'A' && c[r] <= 'Z' ) { r ++; } System.out.println( "R" + s.substring( r ) + "C" + fromLetters( s.substring( 0, r ) ) ); } } } private static int fromLetters( String s ) { int r = 0; int l = s.length(); for ( int i = 0; i < l; i ++ ) { r = r * 26 + s.charAt( i ) - 'A'; } r ++; for ( int i = 1, c = 26; i < l; i ++, c *= 26 ) { r += c; } return r; } private static String toLetters( String s ) { int x = new Integer( s ) - 1; int c = 26; int l = 1; while ( true ) { if ( x < c ) { String r = ""; for ( int i = 0; i < l; i ++ ) { r = ( char ) ( 'A' + x % 26 ) + r; x /= 26; } return r; } x -= c; c *= 26; l ++; } } private static boolean isNumber( String s ) { try { int x = new Integer( s ); } catch ( NumberFormatException e ) { return false; } return true; } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; public class B { /** * @param args * @throws IOException */ static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; static HashMap<Character, Integer> val = new HashMap<Character, Integer>(); static HashMap<Integer, Character> ch = new HashMap<Integer, Character>(); static StringBuffer strcol = new StringBuffer(); static String s; static boolean isDigit(char a) { boolean found = false; for (int i = 0; i < digits.length; i++) { if (found = a == digits[i]) break; } return found; } static String ABtoRC(int pos) { do { ++pos; } while(!isDigit(s.charAt(pos))); int res = 0; for (int i = pos - 1, pow = 1; i >= 0; i--, pow *= 26) { res += val.get(s.charAt(i)) * pow; } return new String("R" + s.substring(pos, s.length()) + "C" + String.valueOf(res)); } static String RCtoAB(int cpos) { int col = Integer.valueOf(s.substring(cpos + 1, s.length())); int mod = 0; strcol.delete(0, strcol.length()); while (col >= 26) { int tmp = col / 26; mod = col - 26 * tmp; if (mod == 0) { mod += 26; tmp -= 1; } col = tmp; strcol.append(ch.get(mod)); } if(col != 0)strcol.append(ch.get(col)); strcol.reverse(); return strcol.toString() + s.substring(1, cpos); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // BufferedReader input = new BufferedReader(new FileReader("input.txt")); // PrintWriter output = new PrintWriter(new FileWriter("output.txt")); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out)); StreamTokenizer in = new StreamTokenizer(input); in.nextToken(); int n = (int)in.nval; for (int i = 0; i < 26; i++) { val.put((char)('A' + i), i + 1); } for (int i = 0; i < 26; i++) { ch.put(i + 1, (char)('A' + i)); } input.readLine(); for (int i = 0; i < n; i++) { s = input.readLine(); int cpos; if( ((cpos = s.indexOf('C')) > 1) && (isDigit(s.charAt(cpos - 1))) ) { output.println(RCtoAB(cpos)); } else { output.println(ABtoRC(cpos)); } } output.close(); input.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RoundOneProblemB { /** * @param args */ public static void main(String[] args) { int n=1; BufferedReader input = new BufferedReader(new InputStreamReader(System.in), 50); try { n = Integer.valueOf(input.readLine()); if (! ((1 <= n) && (n <= Math.pow(10, 5)))) { formatError(); } Pattern typeOne = Pattern.compile("^([A-Z]+)([0-9]+)$"); Pattern typeTwo = Pattern.compile("^R([0-9]+)C([0-9]+)$"); for (int i=0; i < n; i++) { String line = input.readLine(); Matcher matchOne = typeOne.matcher(line); if (matchOne.find()) { System.out.println(convertOneToTwo(matchOne.group(2), matchOne.group(1))); } else { Matcher matchTwo = typeTwo.matcher(line); if (matchTwo.find()) { System.out.println(convertTwoToOne(matchTwo.group(1), matchTwo.group(2))); } } } } catch (Exception e) { formatError(); } } private static String convertTwoToOne(String row, String col) { StringBuilder result = new StringBuilder(); long c = Long.parseLong(col); while ( c > 0) { result.append((char)(((c-1) % 26)+'A')); c = (c-1) / 26; } result.reverse(); result.append(Long.parseLong(row)); return result.toString(); } private static String convertOneToTwo(String row, String col) { StringBuilder result = new StringBuilder(); int l = col.length(); col = col.toUpperCase(); long base = 1; long c = 0; for (int i=l-1; i >= 0; i--) { c = c + ((col.charAt(i) - 'A' + 1) * base); base = base * 26; } result.append("R").append(Long.parseLong(row)).append("C").append(c); return result.toString(); } /** * Exit with an error due to unexpected standard input. */ private static void formatError() { System.out.println("Unexpected input"); System.exit(1); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.util.*; public class Elektronnietablici { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer in; static PrintWriter out = new PrintWriter(System.out); public static String nextToken() throws IOException{ while (in == null || !in.hasMoreTokens()){ in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } public static double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } public static void main(String[] args) throws IOException{ int n = nextInt(); String S; for (int i = 0; i < n; i++) { S = nextToken(); int f = 0; if (S.charAt(0) == 'R' && S.charAt(1) >= '1' && S.charAt(1) <= '9'){ for (int j = 2; j < S.length(); j++) { if (S.charAt(j) >= 'A' && S.charAt(j) <= 'Z'){ f = 1; break; } } } if (f == 0){ String T1 = ""; String ans = "R"; int j; for (j = 0; S.charAt(j) >= 'A' && S.charAt(j) <= 'Z'; j++) { T1 += S.charAt(j); } ans += S.substring(j, S.length()) + "C"; int len = j; j--; int p = 1; int z = 0; for (; j >= 0; j--) { z += (S.charAt(j) - 'A') * p; p *= 26; } p = 1; for (int k = 0; k < len; k++) { z += p; p *= 26; } ans += z; out.println(ans); } else{ String T1 = ""; String ans = ""; int j; for (j = 1; S.charAt(j) != 'C'; j++) { ans += S.charAt(j); } T1 = S.substring(j + 1, S.length()); int z = Integer.parseInt(T1); int p = 1; int len = 0; while (p <= z){ z -= p; p *= 26; len++; } p /= 26; T1 = ""; for (int k = len - 1; k >= 0; k--) { int l = z / p; T1 += (char)(z / p + 'A'); z -= l * p; p /= 26; } ans = T1 + ans; out.println(ans); } } //2 //R23C55 //BC23 out.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; public class MSpreadSheet { public int toNum(String x) { int result = 0; int pow = 0; for (int i = x.length()-1; i >=0; i--) { result+=(x.charAt(i)-'A'+1)*Math.pow(26, pow); pow++; } return result; } public String toString(int x) { if(x<=26) return String.valueOf((char)(x+'A'-1)); String result = ""; while(x!=0) { if(x%26==0) { result = 'Z' + result; x = x/26 - 1; } else { result = (char)((x%26)+'A'-1) + result; x = x/26; } } return result; } public boolean check(String x) { if(x.charAt(0)!='R') return false; //first rep int in = x.indexOf('C'); if(in==-1) return false; if(Character.isDigit(x.charAt(in-1))&&Character.isDigit(x.charAt(in+1))) return true; return false; } public void solve(String x) { String r=""; String c=""; if(check(x)) { int in = x.indexOf('C'); r = x.substring(1,in); c = x.substring(in+1); System.out.println(toString(Integer.parseInt(c))+r); } else { int i =0; while(!Character.isDigit(x.charAt(i))) c+=x.charAt(i++); while(i<x.length()) r+=x.charAt(i++); System.out.println("R"+r+"C"+toNum(c)); } } public static void main(String[] args) { MSpreadSheet sh = new MSpreadSheet(); Scanner s = new Scanner(System.in); int n = s.nextInt(); int i = 0; while(i<n) { sh.solve(s.next()); i++; } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.*; import java.io.*; public class Solution extends Thread { final static int MAXNUM = 1 << 20; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); int tests = nextInt(); int num = 1; for (int test = 0; test < tests; test++) { String s = next(); if (s.charAt(0) == 'R' && s.charAt(1) >= '0' && s.charAt(1) <= '9' && s.indexOf('C') != -1) { String[] sp = s.split("[RC]"); int r = Integer.parseInt(sp[1]); int c = Integer.parseInt(sp[2]); s = ""; while (c > 0) { if (c % 26 == 0) { s = 'Z' + s; c /= 26; c --; } else { s = (char)('A' + c % 26 - 1) + s; c /= 26; } } s = s + r; } else { int pos = 0; while (s.charAt(pos) < '0' || s.charAt(pos) > '9') { pos ++; } int r = Integer.parseInt(s.substring(pos)); int c = 0; s = s.substring(0, pos); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) < 'Z') { c = c * 26 + (s.charAt(i) - 'A' + 1); } else { c = c * 26 + 26; } } s = "R" + r + "C" + c; } System.out.println(s); } } catch (Exception ex) { ex.printStackTrace(); System.exit(-1); } } String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } BufferedReader in; StringTokenizer st; public static void main(String[] args) { Locale.setDefault(Locale.US); new Thread(new Solution()).start(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; public class B { public static void main (String[] args) throws IOException { BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(b.readLine()); while (n-- > 0) { String s = b.readLine(); if (s.matches("^[A-Z]+[0-9]+$")) { System.out.println(toRC(decodeCR(s))); } else { System.out.println(toCR(decodeRC(s))); } } } private static String toRC(int[] a) { return "R" + a[0] + "C" + a[1]; } private static String toCR(int[] a) { String r = ""; if (a[1] == 1) { r = "A"; } else { for (int x = a[1]; x > 0; x /= 26) { r = (char)('A' + (x - 1) % 26) + r; if (x % 26 == 0) x -= 26; } } return r + a[0]; } private static int[] decodeCR(String s) { int[] a = new int[2]; int i = 0; while (s.charAt(i) >= 'A') { a[1] = a[1] * 26 + (s.charAt(i) - 'A' + 1); i++; } a[0] = Integer.parseInt(s.substring(i)); // System.out.println("decoding CR: " + s + "..." + a[0] + ", " + a[1]); return a; } private static int[] decodeRC(String s) { assert s.charAt(0) == 'R'; int[] a = new int[2]; a[0] = Integer.parseInt(s.substring(1, s.indexOf('C'))); a[1] = Integer.parseInt(s.substring(s.indexOf('C') + 1)); // System.out.println("decoding RC: " + s + "..." + a[0] + ", " + a[1]); return a; } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class B1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCount = in.nextInt(); for (int test = 0; test < testCount; test++) { String src = in.next(); if (src.matches("^R\\d+C\\d+$")) { Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(src); m.find(); int r = Integer.parseInt(m.group(0)); m.find(); int c = Integer.parseInt(m.group(0)); System.out.println(toBase26(c) + r); } else { Pattern p = Pattern.compile("[A-Z]+"); Matcher m = p.matcher(src); m.find(); String c = m.group(0); p = Pattern.compile("\\d+"); m = p.matcher(src); m.find(); int r = Integer.parseInt(m.group(0)); System.out.println("R" + r + "C" + toBase10(c)); } } } private static String toBase26(int n) { String res = ""; do { n -= 1; res = (char)('A' + (n % 26)) + res; n /= 26; } while (n > 0); return res; } private static int toBase10(String x) { int n = 0; char[] digits = x.toCharArray(); for (int i = 0; i < digits.length; i++) { n *= 26; n += digits[i] - 'A' + 1; } return n; } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class ProbB implements Runnable { private boolean _ReadFromFile = false; private boolean _WriteToFile = false; static final String TASK_ID = "in"; static final String IN_FILE = TASK_ID + ".in"; static final String OUT_FILE = TASK_ID + ".out"; static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; private static String alphabet; private static void core() throws Exception { int n = nextInt(); alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int test = 0; test < n; test++) { String input = reader.readLine(); StringTokenizer st = new StringTokenizer(input, alphabet); ArrayList<Integer> have = new ArrayList<Integer>(); while (st.hasMoreElements()) { String kString = st.nextToken(); have.add(Integer.parseInt(kString)); } if (have.size() == 2) writer.println(twoInts(have.get(0), have.get(1))); else { String row = ""; int col = 0; for (int i = 0; i < input.length(); i++) { if (Character.isDigit(input.charAt(i))) { row = input.substring(0, i); col = Integer.parseInt(input.substring(i)); break; } } writer.println(oneInt(row, col)); } } } private static String oneInt(String row, int col) { return "R" + col + "C" + toNum(row); } private static int toNum(String row) { int res = 0; for (int i = 0; i < row.length(); i++) { res = res * 26 + row.charAt(i) - 'A' + 1; } return res; } private static String twoInts(Integer row, Integer col) { return toAlpha(col) + row; } private static String toAlpha(Integer col) { String res = ""; while (col > 0) { if (col % 26 > 0) { res = alphabet.charAt(col % 26 - 1) + res; col /= 26; } else { res = "Z" + res; col -= 26; col /= 26; } } return res; } void debug(Object...os) { System.out.println(Arrays.deepToString(os)); } //--------------------- IO stuffs --------------------- public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ProbB()); thread.start(); thread.join(); } public void run() { try { reader = _ReadFromFile ? new BufferedReader(new FileReader(IN_FILE)) : new BufferedReader(new InputStreamReader(System.in)); writer = _WriteToFile ? new PrintWriter(OUT_FILE) : new PrintWriter(new BufferedOutputStream(System.out)); tokenizer = null; core(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } static int nextInt() throws Exception { return Integer.parseInt(nextToken()); } static long nextLong() throws Exception { return Long.parseLong(nextToken()); } static double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } static String nextToken() throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Round1TaskB implements Runnable { static PrintWriter pw = null; static BufferedReader br = null; StringTokenizer st = null; public static void main(String[] args) throws IOException { pw = new PrintWriter(new OutputStreamWriter(System.out)); br = new BufferedReader(new InputStreamReader(System.in)); (new Thread(new Round1TaskB())).start(); } void nline() { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } int ni() { while (st == null || !st.hasMoreTokens()) nline(); return Integer.valueOf(st.nextToken()); } double nd() { while (st == null || !st.hasMoreTokens()) nline(); return Double.valueOf(st.nextToken()); } long nl() { while (st == null || !st.hasMoreTokens()) nline(); return Long.valueOf(st.nextToken()); } String nwrd() { while (st == null || !st.hasMoreTokens()) nline(); return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { } return null; } boolean isDigit(char c) { if (c <= '9' && c >= '0') return true; return false; } void rec(int t, int length) { if (length == 0) { return; } rec(t / 26, length - 1); pw.print((char) ('A' + (t % 26))); } void RC(int i, int j) { int num = 0; for (int t = i; t < j; t++) { num = num * 10 + format[t] - '0'; } int len = 0, base = 1, total = 0; while (true) { base *= 26; total += base; len++; if (num <= total) break; } num -= total / 26; rec(num, len); } void BC(int i, int j) { int total = 0, base = 1, rest = 0; for (int k = i; k< j; k++) { total += base; base *= 26; rest = rest * 26 + format[k] - 'A'; } pw.print(total + rest); } char format[]; public void solve() { format = nwrd().toCharArray(); int L = format.length; for (int i = 0; i < L - 1; i++) { if (isDigit(format[i]) && (format[i + 1] == 'C')) { RC(i + 2, L); for (int j = 1; j <= i; j++) { pw.print(format[j]); } pw.println(); return; } } for (int i = 0; i < L; i++) { if (isDigit(format[i])) { pw.print('R'); for (int j = i; j < L; j++) { pw.print(format[j]); } pw.print('C'); BC(0, i); pw.println(); return; } } } public void run() { int n = ni(); while (n-- > 0) { solve(); } pw.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class Task1b { static int[] fromRC (String data) { int pos = data.indexOf('C'); int res[] = new int[2]; res[0] = Integer.parseInt(data.substring(1, pos)); res[1] = Integer.parseInt(data.substring(pos + 1)); return res; } static int[] fromXC (String data) { int pos = 0; int res[] = new int[2]; res[0] = res[1] = 0; while (data.charAt(pos) >= 'A' && data.charAt(pos) <= 'Z') { res[1] *= 26; res[1]++; res[1] += data.charAt(pos) - 'A'; pos++; } res[0] = Integer.parseInt(data.substring(pos)); return res; } static String toRC (int[] data) { return String.format("R%dC%d", data[0], data[1]); } static String toXC (int[] data) { StringBuilder sb = new StringBuilder(); while (data[1] > 0) { data[1]--; sb.append((char)('A' + data[1] % 26)); data[1] /= 26; } sb = sb.reverse(); sb.append(data[0]); return sb.toString(); } /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for (int i = 0; i < n; i++) { String s = br.readLine(); if ((s.charAt(0) == 'R') && (s.charAt(1) >= '0' && s.charAt(1) <= '9') && (s.indexOf('C') != -1)) { System.out.println(toXC(fromRC(s))); } else { System.out.println(toRC(fromXC(s))); } } } }
linear
1_B. Spreadsheets
CODEFORCES
// by kotb import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SpreadSheet { public void run() { try { Scanner s = new Scanner(System.in); int tests = s.nextInt(); for (int i = 0; i < tests; i++) { String line = s.next(); String regex = "R[\\d]+C[\\d]+"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(line); if (matcher.matches()){ int r = Integer.parseInt(line.substring(1, line.indexOf("C"))); int c = Integer.parseInt(line.substring(line.indexOf("C") +1)); System.out.println(toFormula(r, c)); } else { int index = -1; for (int j = 0; j < line.length(); j++) { if (line.charAt(j) >= '0' && line.charAt(j) <= '9') { index = j; break; } } String c = line.substring(0, index); int r = Integer.parseInt(line.substring(index)); System.out.println(fromFormula(c, r)); } } } catch (Exception e) { e.printStackTrace(); } } private String toFormula(int r, int c) { StringBuffer buff = new StringBuffer(); char ch; while (c != 0) { int m = c%26; if(m==0) { ch = 'Z'; c = c/26 - 1; } else { ch = (char)(m+'A'-1); c /= 26; } buff.append(ch); } return buff.reverse().toString() + r; } private String fromFormula(String c, int r) { int ret = 0; int power = 1; for (int i = c.length()-1; i >= 0; i--) { ret += ((c.charAt(i) - 'A' + 1) * power); power *= 26; } return "R" + r + "C" + ret; } public static void main(String[] args) { new SpreadSheet().run(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.regex.*; //import java.math.*; //import static java.lang.Math.*; //import static java.util.Arrays.*; public class Main{ public static void main(String[] args) throws IOException { //1-checker 2-console //if (args.length==2) open(args[0], args[1], true, false); else open ("input.txt", "output.txt", true, false); open ("input.txt", "output.txt", false, true); char[] alph = " ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); Pattern pat = Pattern.compile("[A-Z]+[\\d]+"); Matcher mat; boolean b ; String s; int index, coef, row, col; int n = nextInt(); String[] tmp; char[] c; for (int i=0; i<n; i++) { s = nextLine(); c = s.toCharArray(); mat = pat.matcher(s); b = mat.matches(); if (b) { index = c.length-1; coef = 1; row = 0; while (c[index]>='0' && c[index]<='9') { row += (c[index]-'0')*coef; coef*=10; index--; } coef = 1; col = 0; while (index>=0) { /*if (coef!=1)*/ col += (Arrays.binarySearch(alph, c[index]))*coef; //else col += (Arrays.binarySearch(alph, c[index]))*coef; coef*=26; index--; } out.println("R"+row+"C"+col); } else { tmp = s.split("R|C"); //out.print(tmp.length); //row = Integer.parseInt(tmp[1]); col = Integer.parseInt(tmp[2]); char[] temp = new char[10]; int len = 0; int v = 0; while (col>0) { index = col%26; if (index==0) { index=26; v = 1; } else v = 0; /*if (len==0)*/ temp[len]=alph[index]; //else temp[len]=alph[index-1]; col = (col/26) - v; len++; } for (int j=len-1; j>=0; j--) { out.print(temp[j]); } out.println(tmp[1]); } } close(); } static StringTokenizer st; static StreamTokenizer strTok; static BufferedReader in; static PrintWriter out; static String nextToken(boolean f) throws IOException { if (f) { return in.readLine(); } else { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } } static String nextLine() throws IOException { return nextToken(true); } static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken(false)); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken(false)); } static double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken(false)); } static char nextChar() throws IOException { return ((char)in.read()); } static void close(){ out.flush(); out.close(); } static void open(String filein, String fileout, boolean flag, boolean console) throws IOException{ if (flag) { strTok = new StreamTokenizer(new FileReader (new File(filein))); in = new BufferedReader(new FileReader (new File(filein))); out = new PrintWriter(new FileWriter(new File (fileout))); } else { if (console){ strTok = new StreamTokenizer(new InputStreamReader (System.in, "ISO-8859-1")); in = new BufferedReader (new InputStreamReader (System.in, "ISO-8859-1")); out = new PrintWriter (new OutputStreamWriter (System.out, "ISO-8859-1")); } else { strTok = new StreamTokenizer(new FileReader (new File("input.txt"))); in = new BufferedReader(new FileReader (new File("input.txt"))); out = new PrintWriter(new FileWriter(new File ("output.txt"))); } } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class B { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedReader(new InputStreamReader( System.in))); int nc = sc.nextInt(); while (nc-- > 0) { String s = sc.next(); StringTokenizer st = new StringTokenizer(s, "0123456789"); if (st.countTokens() > 1) { int k = s.indexOf('C'); int r = Integer.parseInt(s.substring(1, k)); int c = Integer.parseInt(s.substring(k + 1)); int len = 1; int p = 26; while (c > p) { c -= p; len++; p *= 26; } String col = Integer.toString(--c, 26).toUpperCase(); while (col.length() < len) col = "0" + col; StringBuilder sb = new StringBuilder(); for (int i = 0; i < col.length(); i++) { if (col.charAt(i) < 'A') { sb.append((char) (col.charAt(i) - '0' + 'A')); } else { sb.append((char) (col.charAt(i) + 10)); } } System.out.printf("%s%d\n", sb.toString(), r); } else { int k = 0; while (s.charAt(k) > '9') k++; char[] col = s.substring(0, k).toCharArray(); int r = Integer.parseInt(s.substring(k)); int c = 1; int p = 26; int cnt = 1; while (cnt++ < col.length) { c += p; p *= 26; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < col.length; i++) { if (s.charAt(i) < 'K') { sb.append((char) ('0' + col[i] - 'A')); } else { sb.append((char) (col[i] - 10)); } } c += Integer.parseInt(sb.toString(), 26); System.out.printf("R%dC%d\n", r, c); } } System.out.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int MAXDEG = 5; void gen() throws FileNotFoundException { PrintWriter out = new PrintWriter("input.txt"); int n = 100000; Random rnd = new Random(); out.println(n); for (int i = 0; i < n; i++) { out.println("R" + (rnd.nextInt(1000000) + 1) + "C" + (rnd.nextInt(1000000) + 1)); } out.close(); } void gen2() throws FileNotFoundException { PrintWriter out = new PrintWriter("input.txt"); int n = 100000; Random rnd = new Random(); out.println(n); for (int i = 0; i < n; i++) { int len = rnd.nextInt(MAXDEG) + 1; String pref = ""; for (int j = 0; j < len; j++) pref += (char) (rnd.nextInt(26) + 'A'); out.println(pref + (rnd.nextInt(1000000) + 1)); } out.close(); } private void run() throws IOException { // gen2(); // if (true) return; // System.setOut(new PrintStream("output.txt")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int[] sumDegs = new int[MAXDEG + 1]; sumDegs[0] = 1; int deg = 1; for (int i = 1; i <= MAXDEG; i++) { deg *= 26; sumDegs[i] = sumDegs[i - 1] + deg; } for (int i = 0; i < n; i++) { String s = nextLine(); String pref = ""; int endPos = -1; for (int j = 0; j < s.length(); j++) { if (!isLet(s.charAt(j))) { endPos = j; break; } pref += s.charAt(j); } int num = -1; try { num = Integer.parseInt(s.substring(endPos)); } catch (Exception e) { } if (num != -1) { int col = sumDegs[pref.length() - 1]; int val = 0; for (int j = 0; j < pref.length(); j++) { val = val * 26 + (pref.charAt(j) - 'A'); } col += val; out.println("R" + num + "C" + col); } else { int row = Integer.parseInt(s.substring(1, s.indexOf('C'))); int col = Integer.parseInt(s.substring(s.indexOf('C') + 1)); int len = MAXDEG; while (col < sumDegs[len]) len--; len++; col -= sumDegs[len - 1]; String res = ""; while (col > 0) { res = (char) (col % 26 + 'A') + res; col /= 26; } while (res.length() < len) res = "A" + res; out.println(res + row); } } in.close(); out.close(); } private boolean isLet(char c) { return c >= 'A' && c <= 'Z'; } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SpreadSheet { public void run() { try { Scanner s = new Scanner(System.in); int tests = s.nextInt(); for (int i = 0; i < tests; i++) { String line = s.next(); String regex = "R[\\d]+C[\\d]+"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(line); if (matcher.matches()){ int r = Integer.parseInt(line.substring(1, line.indexOf("C"))); int c = Integer.parseInt(line.substring(line.indexOf("C") +1)); System.out.println(toFormula(r, c)); } else { int index = -1; for (int j = 0; j < line.length(); j++) { if (line.charAt(j) >= '0' && line.charAt(j) <= '9') { index = j; break; } } String c = line.substring(0, index); int r = Integer.parseInt(line.substring(index)); System.out.println(fromFormula(c, r)); } } } catch (Exception e) { e.printStackTrace(); } } private String toFormula(int r, int c) { StringBuffer buff = new StringBuffer(); char ch; while (c != 0) { int m = c%26; if(m==0) { ch = 'Z'; c = c/26 - 1; } else { ch = (char)(m+'A'-1); c /= 26; } buff.append(ch); } return buff.reverse().toString() + r; // String ret = ""; // StringBuffer buff = new StringBuffer(); // while (c != 0) { // int m = c%26; // char ch = (char)(m+'A'-1); // buff.append(ch); // c /= 26; // } // return buff.reverse().toString() + r; } private String fromFormula(String c, int r) { int ret = 0; int power = 1; for (int i = c.length()-1; i >= 0; i--) { ret += ((c.charAt(i) - 'A' + 1) * power); power *= 26; } return "R" + r + "C" + ret; } public static void main(String[] args) { new SpreadSheet().run(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Problem solution template. * @author Andrew Porokhin, [email protected] */ public class Problem01B implements Runnable { static final long[] x10 = new long[] { 1, 26, 26*26, 26*26*26, 26*26*26*26, 26*26*26*26*26, 26*26*26*26*26*26}; void solve() throws NumberFormatException, IOException { // TODO: Write your code here ... int n = nextInt(); for (int i = 0; i < n; i++) { String t = nextToken().toUpperCase(); StringBuffer rowString = new StringBuffer(t.length()); StringBuffer numb1 = new StringBuffer(t.length()); StringBuffer numb2 = new StringBuffer(t.length()); int stage = 0; for (int j = 0; j < t.length(); j++) {; char charAt = t.charAt(j); if (charAt >= 'A') { if (stage == 0) { rowString.append(charAt); } else { stage++; } } else { if (stage == 0 || stage == 2) stage++; switch (stage) { case 1: numb1.append(charAt); break; case 3: numb2.append(charAt); break; } } } if (stage == 1) { long result = convertString(rowString); System.out.print("R"); System.out.print(numb1.toString()); System.out.print("C"); System.out.println(result); } else { StringBuffer tmp = convertNumber(Long.parseLong(numb2.toString())); System.out.print(tmp.toString()); System.out.println(numb1.toString()); } } } public StringBuffer convertNumber(long n) { StringBuffer sb2 = new StringBuffer(); long nmod26 = n % 26; long ndiv26 = n / 26; while (ndiv26 > 0 || nmod26 > 0) { long tmp = 0; if (nmod26 > 0) { sb2.append((char) ('A' + nmod26 - 1)); tmp = ndiv26; } else { sb2.append('Z'); tmp = ndiv26 - 1; } nmod26 = tmp % 26; ndiv26 = tmp / 26; } return sb2.reverse(); } public long convertString(StringBuffer sb) { long result = 0; for (int i = 0; i < sb.length(); i++) { long l = (sb.charAt(i) - 'A' + 1) * x10[sb.length() - i - 1]; result += l; } return result; } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) { new Problem01B().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { System.exit(9000); } finally { out.flush(); out.close(); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Scanner; public class TaxiDriversAndLyft2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long m = scanner.nextLong(); long[] people = new long[(int) (n+m)]; int[] taxiDrivers = new int[(int) (n+m)]; for(int i = 0;i< (n+m); i++) { people[i] = scanner.nextLong(); } for(int i = 0;i< (n+m); i++) { taxiDrivers[i] = scanner.nextInt(); } int lastTaxiDriverIndex = -1; long[] riderCountArray = new long[(int) (m)]; long[] a1 = new long[(int)n]; long[] b1 = new long[(int)m]; int j=0, k=0; for(int i = 0;i< (n+m); i++) { if(taxiDrivers[i] == 0) { a1[j] = people[i]; j++; } else { b1[k] = people[i]; k++; } } int l = 0, q=0; for(int i=0;i<j;i++) { while ((l<m-1 && m>1) && Math.abs(a1[i] - b1[l]) > Math.abs(a1[i] - b1[l+1])) { l++; } riderCountArray[l]++; } for(int i = 0;i< (m); i++) { System.out.print(riderCountArray[i]+" "); } } }
linear
1075_B. Taxi drivers and Lyft
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] P = new int[n]; int[] check=new int[n]; for (int i = 1; i < n; i++) { P[i] = scanner.nextInt(); P[i]--; check[P[i]]++; } int[] leaves = new int[n]; for (int i=0;i<n;i++) { if(check[i]==0){ leaves[P[i]]++; } } for (int i = 0; i < n; i++) { if (check[i]>0&&leaves[i]<3) { System.out.println("No"); return; } } System.out.println("Yes"); } }
linear
913_B. Christmas Spruce
CODEFORCES
import java.util.HashSet; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0; i<n; i++){ int a = sc.nextInt(); if(a!=0){ set.add(a); } } System.out.println(set.size()); } }
linear
992_A. Nastya and an Array
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args){ Scanner s= new Scanner(System.in); int n=s.nextInt();StringBuilder sb=new StringBuilder(); long[] a=new long[n/2]; for(int i=0;i<n/2;i++){ a[i]=s.nextLong(); }int j=0;long[] a2=new long[n/2];long[] a1=new long[n/2]; a1[j]=a[a.length-1]/2; a2[j]=a[a.length-1]-a[a.length-1]/2; for(int i=(n-1)/2-1;i>=0;i--){ // a1[j]=a[i]/2;a2[j++]=a[i]-a[i]/2; long n1=a1[j]; if((a[i]-n1)<a2[j]){ a2[j+1]=a2[j++];a1[j]=a[i]-a2[j]; }else{a1[++j]=n1;a2[j]=a[i]-n1;} }int k=0;//int[] ans=new int[2*n]; for(int i=(n-1)/2;i>=0;i--) sb.append(a1[i]+" "); for(int i=0;i<n/2;i++) sb.append(a2[i]+" "); System.out.println(sb.toString()); } }
linear
1093_C. Mishka and the Last Exam
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; public class alex { public static void main(String[] args)throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt();int sum=1; for(int i=1;i<=n;i++) { sum=sum+(4*(i-1)); } System.out.println(sum); } }
linear
1180_A. Alex and a Rhombus
CODEFORCES
import java.io.*; import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n = in.nextInt(); int m = in.nextInt(); long boyMax = 0; int NBoyMax = 0; long sweets = 0; TreeSet<Long> boyMember = new TreeSet<>(); for (int i = 0; i < n; i++) { long input = in.nextLong(); boyMember.add(input); if (boyMax < input) { boyMax = input; NBoyMax = 1; } else if (boyMax == input) NBoyMax++; sweets += (input * m); } long smallestGirl = (long) 1e8 + 1; long sum = 0; for (int i = 0; i < m; i++) { long input = in.nextLong(); sum += input; if (smallestGirl > input) smallestGirl = input; } if (smallestGirl < boyMember.last()) { out.println(-1); } else if (smallestGirl == boyMember.last()) { sweets += sum - boyMember.last() * m; out.println(sweets); } else { if (NBoyMax > 1) { sweets += sum - boyMember.last() * m; out.println(sweets); } else { Object[] boyList = boyMember.toArray(); if (boyList.length > 1) { long boy = 0; boy = (long)boyList[boyList.length - 2]; sweets += (sum - smallestGirl - boyMember.last() * (m - 1)); sweets += (smallestGirl - boy); out.println(sweets); } else { out.println(-1); } } } in.close(); out.close(); } }
linear
1159_C. The Party and Sweets
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class Main { static Scanner sc = new Scanner (System.in); public static void main(String[] args) { int n = sc.nextInt(); int k = sc.nextInt(); char str[][] = new char[5][n]; for(int i = 0;i < 4;i ++){ for(int j = 0;j < n;j ++) str[i][j] = '.'; } if(k % 2 == 0){ k /= 2; for(int i = 1;i <= 2;i++){ for(int j = 1;j <= k;j++) str[i][j] = '#'; } } else{ str[1][n / 2] = '#'; if(k != 1){ int tmp = n / 2; if(k <= n - 2){ for(int i = 1;i<= (k - 1) / 2;i++){ str[1][i] = '#'; str[1][n - 1 - i] = '#'; } } else{ for(int i = 1;i <= n - 2;i++) str[1][i] = '#'; k -= n - 2; for(int i = 1;i <= k/2;i++){ str[2][i] = '#'; str[2][n - 1 - i]='#'; } } } } System.out.println("YES"); for(int i = 0;i < 4;i ++){ System.out.println(str[i]); } } }
linear
980_B. Marlin
CODEFORCES
import java.io.*; public class First { StreamTokenizer in; PrintWriter out; int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } void run() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); solve(); out.flush(); } void solve() throws IOException { int n = nextInt(), k = nextInt(), sum = 0, count = 0; String str = nextString(); char[] arr = str.toCharArray(); boolean[] bool = new boolean[26]; for(char ch: arr){ bool[((int)ch)-97] = true; } for(int i = 0; i < 26; i++){ if(bool[i]){ sum += i+1; count++; i += 1; } if(count == k) break; } if(count == k) out.println(sum); else out.println(-1); } public static void main(String[] args) throws IOException { new First().run(); } }
linear
1011_A. Stages
CODEFORCES
import java.io.*; public class First { StreamTokenizer in; PrintWriter out; int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } void run() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); solve(); out.flush(); } void solve() throws IOException { int n = nextInt(), k = nextInt(), sum = 0, count = 0; String str = nextString(); char[] arr = str.toCharArray(); boolean[] bool = new boolean[26]; for(char ch: arr){ bool[((int)ch)-97] = true; } for(int i = 0; i < 26; i++){ if(bool[i]){ sum += i+1; count++; i += 1; } if(count == k) break; } if(count == k) out.println(sum); else out.println(-1); } public static void main(String[] args) throws IOException { new First().run(); } }
linear
1011_A. Stages
CODEFORCES
import java.util.*; import java.io.*; public class Solution { public static void main(String [] args) throws IOException { PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); /* inputCopy 5 3 xyabd outputCopy 29 inputCopy 7 4 problem outputCopy 34 inputCopy 2 2 ab outputCopy -1 inputCopy 12 1 abaabbaaabbb outputCopy 1 */ int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); st=new StringTokenizer(br.readLine()); String str=st.nextToken(); char [] arr=str.toCharArray(); Arrays.sort(arr); int weight=arr[0]-96; char a=arr[0]; int included=1; for(int i=1;i<arr.length;++i) { if(included==k) break; char c=arr[i]; if(c-a<2) continue; weight+=arr[i]-96; ++included; a=arr[i]; } if(included==k) pw.println(weight); else pw.println(-1); pw.close();//Do not forget to write it after every program return statement !! } } /* →Judgement Protocol Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 5 3 xyabd Output 29 Answer 29 Checker Log ok 1 number(s): "29" Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 7 4 problem Output 34 Answer 34 Checker Log ok 1 number(s): "34" Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ab Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 12 1 abaabbaaabbb Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 13 qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa Output 169 Answer 169 Checker Log ok 1 number(s): "169" Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 14 qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 a Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 2 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 13 13 uwgmkyqeiaocs Output 169 Answer 169 Checker Log ok 1 number(s): "169" Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 13 13 hzdxpbfvrltnj Output 182 Answer 182 Checker Log ok 1 number(s): "182" Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 n Output 14 Answer 14 Checker Log ok 1 number(s): "14" Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 10 8 smzeblyjqw Output 113 Answer 113 Checker Log ok 1 number(s): "113" Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 20 20 tzmvhskkyugkuuxpvtbh Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 30 15 wjzolzzkfulwgioksfxmcxmnnjtoav Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 40 30 xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 31 ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 10 7 iuiukrxcml Output 99 Answer 99 Checker Log ok 1 number(s): "99" Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 38 2 vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa Output 5 Answer 5 Checker Log ok 1 number(s): "5" Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 12 6 fwseyrarkwcd Output 61 Answer 61 Checker Log ok 1 number(s): "61" Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ac Output 4 Answer 4 Checker Log ok 1 number(s): "4" Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 c Output 3 Answer 3 Checker Log ok 1 number(s): "3" Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ad Output 5 Answer 5 Checker Log ok 1 number(s): "5" Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER Input 2 1 ac Output -1 Answer 1 Checker Log wrong answer 1st number */
linear
1011_A. Stages
CODEFORCES
import java.util.*; import java.io.*; public class Solution { public static void main(String [] args) throws IOException { PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); /* inputCopy 5 3 xyabd outputCopy 29 inputCopy 7 4 problem outputCopy 34 inputCopy 2 2 ab outputCopy -1 inputCopy 12 1 abaabbaaabbb outputCopy 1 */ int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); st=new StringTokenizer(br.readLine()); String str=st.nextToken(); char [] arr=str.toCharArray(); Arrays.sort(arr); int weight=arr[0]-96; char a=arr[0]; int included=1; for(int i=1;i<arr.length;++i) { if(included==k) break; char c=arr[i]; if(c-a<2) continue; weight+=arr[i]-96; ++included; a=arr[i]; } if(included==k) pw.println(weight); else pw.println(-1); pw.close();//Do not forget to write it after every program return statement !! } } /* →Judgement Protocol Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 5 3 xyabd Output 29 Answer 29 Checker Log ok 1 number(s): "29" Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 7 4 problem Output 34 Answer 34 Checker Log ok 1 number(s): "34" Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ab Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 12 1 abaabbaaabbb Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 13 qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa Output 169 Answer 169 Checker Log ok 1 number(s): "169" Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 14 qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 a Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Output 1 Answer 1 Checker Log ok 1 number(s): "1" Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 2 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 13 13 uwgmkyqeiaocs Output 169 Answer 169 Checker Log ok 1 number(s): "169" Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 13 13 hzdxpbfvrltnj Output 182 Answer 182 Checker Log ok 1 number(s): "182" Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 n Output 14 Answer 14 Checker Log ok 1 number(s): "14" Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 10 8 smzeblyjqw Output 113 Answer 113 Checker Log ok 1 number(s): "113" Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 20 20 tzmvhskkyugkuuxpvtbh Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 30 15 wjzolzzkfulwgioksfxmcxmnnjtoav Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 40 30 xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 50 31 ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz Output -1 Answer -1 Checker Log ok 1 number(s): "-1" Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 10 7 iuiukrxcml Output 99 Answer 99 Checker Log ok 1 number(s): "99" Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 38 2 vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa Output 5 Answer 5 Checker Log ok 1 number(s): "5" Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 12 6 fwseyrarkwcd Output 61 Answer 61 Checker Log ok 1 number(s): "61" Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ac Output 4 Answer 4 Checker Log ok 1 number(s): "4" Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 1 1 c Output 3 Answer 3 Checker Log ok 1 number(s): "3" Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK Input 2 2 ad Output 5 Answer 5 Checker Log ok 1 number(s): "5" Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER Input 2 1 ac Output -1 Answer 1 Checker Log wrong answer 1st number */
linear
1011_A. Stages
CODEFORCES
import java.io.*; import java.util.Scanner; public class abc{ public static int check(StringBuilder s) { int countRemove=0; if(!s.toString().contains("xxx")) return countRemove; else{ for(int i=1;i<s.length()-1;i++) { if(s.charAt(i-1)=='x' && s.charAt(i)=='x' && s.charAt(i+1)=='x') { countRemove++; } } return countRemove; } } public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //sc= new Scanner(System.in); String s = sc.next(); StringBuilder sb = new StringBuilder(""); sb.append(s); System.out.println(check(sb)); } }
linear
978_B. File Name
CODEFORCES
/** * Created by Aminul on 3/14/2019. */ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import static java.lang.Math.max; public class E_2 { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(), k = in.nextInt(), N = (int) 5e6 + 1; int left = 0, right = 0; int a[] = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); if (a[i] == k) left++; } int f[] = new int[N + 1]; int ans = 0; for (int i = n; i >= 1; i--) { if (a[i] == k) left--; f[a[i]]++; f[a[i]] = max(f[a[i]], 1 + right); ans = max(ans, f[a[i]] + left); if (a[i] == k) right++; } pw.println(ans); pw.close(); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = (num << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } }
linear
1082_E. Increasing Frequency
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner in=new Scanner(System.in); String str=in.next(); int cnt=0; for(int i=0;i<str.length();++i) { if(str.charAt(i)=='1') { ++cnt; } } int i=0; for(;i<str.length();++i) { if(str.charAt(i)=='0') { System.out.print("0"); } else if(str.charAt(i)=='2') { while(cnt-->0) {// System.out.print("1"); } System.out.print("2"); } } while(cnt-->0) { System.out.print("1"); } in.close(); } }
linear
1009_B. Minimum Ternary String
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; import java.util.Scanner; /** * * @author Ahmed */ public class Watermelon { static class Passengers { public int floor ; public int time; public Passengers( int floor , int time){ this.floor =floor; this.time =time; } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int x = in.nextInt() , y = in.nextInt(); ArrayList<Passengers> list = new ArrayList<>(); for(int i = 1 ; i <= x ; ++i){ list.add(new Passengers(in.nextInt(), in.nextInt())); } int sum = 0 ; for(int i = list.size() - 1 ; i >= 0 ; --i) { int s = y - list.get(i).floor; sum = sum + s ; if(sum < list.get(i).time) { sum = sum + ( list.get(i).time - sum); } y = list.get(i).floor; } if( list.get(list.size() - 1).floor != 0){ sum = sum + (list.get(0).floor); } System.out.println(sum); } }
linear
608_A. Saitama Destroys Hotel
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class BOOL { static char [][]ch; static int n,m; private static FastReader in =new FastReader(); public static void main(String[] args) { int n=in.nextInt(); int a[]=new int[1000002]; int dp[]=new int[1000002],ans=0; for(int i=0;i<n;i++){a[in.nextInt()]=in.nextInt();} dp[0]=a[0]==0?0:1; for(int i=1;i<1000002;i++){ if(a[i]==0){dp[i]=dp[i-1];} else{ if(a[i]>=i){dp[i]=1;} else{ dp[i]=dp[i-a[i]-1]+1; }} if(dp[i]>=ans)ans=dp[i]; } System.out.println(n-ans); }} class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.Scanner; public class ChainReaction { public static void main(String [] args) { Scanner kb = new Scanner(System.in); int num = kb.nextInt(); int[] beacons = new int[1000002]; for (int i=0; i<num; i++) { beacons[kb.nextInt()] = kb.nextInt(); } int [] dp = new int[1000002]; int max = 0; if (beacons[0] != 0) dp[0] = 1; for (int i=1; i<dp.length; i++) { if (beacons[i] == 0) { dp[i] = dp[i-1]; } else { int index = i-1-beacons[i]; if (index<0) dp[i] = 1; else dp[i] = 1 + dp[index]; } max = Math.max(max, dp[i]); //if (i<11) //System.out.println(i +" is "+dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 0; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 1; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static boolean canWinFromOneMove(char []s,int k) { int prefix=0; int n=s.length; for(int i=0;i<n && s[i]==s[0];i++) prefix++; int suffix=0; for(int i=n-1;i>=0 && s[i]==s[n-1];i--) suffix++; return s[0]==s[n-1] && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(),k=sc.nextInt(); char []s=sc.next().toCharArray(); if(canWinFromOneMove(s, k)) { System.out.println("tokitsukaze"); return; } int []suff=new int [n+1]; suff[n-1]=1; for(int i=n-2;i>=0;i--) { suff[i]=1+(s[i+1]==s[i]?suff[i+1]:0); } for(int i=n-2;i>=0;i--) suff[i]=Math.max(suff[i], suff[i+1]); int max=0,curr=0; boolean draw=false; int ones=0; for(int i=0;i+k<=n;i++) { // one int prefix=ones==i?k+ones:max; int suffix=i+k==n?k:s[i+k]=='1' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k]; char first=i==0?'1':s[0],last=i+k==n?'1':s[n-1]; boolean zero=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; // zero prefix=ones==0?k+ones:max; suffix=i+k==n?k:s[i+k]=='0' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k]; first=i==0?'0':s[0]; last=i+k==n?'0':s[n-1]; boolean one=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n; if(!zero || !one) { // System.err.println(i+1); draw=true; } if(s[i]=='1') ones++; if(i>0 && s[i]==s[i-1] ) curr++; else curr=1; max=Math.max(max, curr); } out.println(draw?"once again":"quailty"); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
linear
1190_C. Tokitsukaze and Duel
CODEFORCES
import java.util.*; import java.io.*; public class C{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new C(); out.flush(); out.close(); } C(){ int a = solve(); out.print(a == 0 ? "tokitsukaze" : a == 1 ? "quailty" : "once again"); } int n, k; char ch[]; int a[], c0 = 0, c1 = 0; TreeSet<Integer> ts[] = new TreeSet[2]; boolean check(){ int min = 0, max = n; if(!ts[0].isEmpty()){ min = ts[0].first(); max = ts[0].last(); if(max - min + 1 > k)return true; } if(!ts[1].isEmpty()){ min = ts[1].first(); max = ts[1].last(); if(max - min + 1 > k)return true; } return false; } int solve(){ n = in.nextInt(); k = in.nextInt(); ch = in.next().trim().toCharArray(); a = new int[n]; for(int i = 0; i < n; i++)c1 += a[i] = ch[i] - '0'; c0 = n - c1; for(int i = 0; i < k; i++){ if(a[i] == 0)c0--; else c1--; } if(c0 == 0 || c1 == 0)return 0; for(int i = k; i < n; i++){ if(a[i] == 0)c0--; else c1--; if(a[i - k] == 0)c0++; else c1++; if(c0 == 0 || c1 == 0)return 0; } for(int i = 0; i < 2; i++)ts[i] = new TreeSet<>(); for(int i = 0; i < n; i++){ ts[a[i]].add(i); } for(int i = 0; i < k; i++){ ts[a[i]].remove(i); } if(check())return 2; for(int i = k; i < n; i++){ ts[a[i]].remove(i); ts[a[i - k]].add(i - k); if(check())return 2; } return 1; } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
linear
1190_C. Tokitsukaze and Duel
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.SortedSet; import java.util.Set; import java.util.NavigableSet; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Niyaz Nigmatullin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int k = in.nextInt(); char[] c = in.next().toCharArray(); NavigableSet<Integer> ones = new TreeSet<>(); NavigableSet<Integer> zeros = new TreeSet<>(); for (int i = 0; i < n; i++) { if (c[i] == '0') zeros.add(i); else ones.add(i); } if (ones.isEmpty() || zeros.isEmpty() || ones.last() - ones.first() + 1 <= k || zeros.last() - zeros.first() + 1 <= k) { out.println("tokitsukaze"); return; } if (check(ones, n, k) && check(zeros, n, k)) { out.println("quailty"); return; } out.println("once again"); } private boolean check(NavigableSet<Integer> ones, int n, int k) { for (int i = 0; i + k <= n; i++) { int left = ones.first(); int right = ones.last(); if (left >= i) { left = ones.higher(i + k - 1); } if (right < i + k) { right = ones.lower(i); } if (right - left + 1 > k) { return false; } } return true; } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } static class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } }
linear
1190_C. Tokitsukaze and Duel
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { public InputReader in; public PrintWriter out; public void solve() throws Exception { // solution goes here int N = in.nextInt(); int[] houses = new int[N]; boolean[] exist = new boolean[52]; for (int i = 0; i < N; i++) { char c = in.nextChar(); if ('a' <= c && c <= 'z') { houses[i] = 26 + (c - 'a'); } else { houses[i] = (c - 'A'); } exist[houses[i]] = true; } int[][] pokemons = new int[N][52]; pokemons[0][houses[0]] = 1; for (int i = 1; i < N; i++) { System.arraycopy(pokemons[i-1], 0, pokemons[i], 0, pokemons[i].length); pokemons[i][houses[i]]++; } int uniques = 0; for(boolean bool : exist) if (bool) uniques++; if (uniques == 1) { out.print(1); return; } int last_variant = -1; for (int i = 0; i < N-1; i++) { if (pokemons[i][houses[i]] == pokemons[N-1][houses[i]]) { last_variant = i; break; } } int minimum = N; for (int i = 0; i <= last_variant; i++) { if (houses[i] == houses[i+1]) continue; // binary search int low = i+1; int high = N-1; while (low < high) { int mid = (low + high) / 2; boolean allPresent = true; for (int j = 0; j < 52; j++) { if (j != houses[i] && exist[j] && pokemons[mid][j] == pokemons[i][j]) { allPresent = false; break; } } if (allPresent) { high = mid; // infinite?? } else { low = mid + 1; } } minimum = min(minimum, low - i + 1); } out.print(minimum); } public void run() { try { in = new InputReader(System.in); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Locale.setDefault(Locale.US); int tests = 1; while (tests-- > 0) { solve(); } out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(7); } } static int abs(int x) { return x < 0 ? -x : x; } static int max(int a, int b) { return a > b ? a : b; } static int min(int a, int b) { return a < b ? a : b; } static long abs(long x) { return x < 0 ? -x : x; } static long max(long a, long b) { return a > b ? a : b; } static long min(long a, long b) { return a < b ? a : b; } public static void main(String args[]) { new Thread(null, new Main(), "Main", 1 << 28).start(); } static boolean OJ = System.getProperty("ONLINE_JUDGE") != null; public void console(Object... objects) { if (!OJ) { out.println(Arrays.deepToString(objects)); out.flush(); } } @SuppressWarnings({"Duplicates", "unused"}) static class InputReader { private InputStream stream; private byte[] buf = new byte[2048]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader() { this.stream = System.in; } public InputReader(InputStream stream) { this.stream = stream; } public InputReader(SpaceCharFilter filter) { this.stream = System.in; this.filter = filter; } public InputReader(InputStream stream, SpaceCharFilter filter) { this.stream = stream; this.filter = filter; } public int read() { if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public int nextDigit() { int c = read(); while (isSpaceChar(c)) c = read(); return c - '0'; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); boolean negative = false; if (c == '-') { negative = true; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public int[] nextInts(int N) { int[] nums = new int[N]; for (int i = 0; i < N; i++) nums[i] = nextInt(); return nums; } public long[] nextLongs(int N) { long[] nums = new long[N]; for (int i = 0; i < N; i++) nums[i] = nextLong(); return nums; } public int nextUnsignedInt() { int c = read(); while (isSpaceChar(c)) c = read(); int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res; } public final long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public final long nextUnsignedLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!(c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1 || c == '.')); if (c != '.') { return res * sgn; } c = read(); long aft = 0; int len = 1; do { if (c < '0' || c > '9') throw new InputMismatchException(); aft *= 10; len *= 10; aft += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn + aft / (1.0 * len); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public char[] nextChars() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); char[] chars = new char[res.length()]; res.getChars(0, chars.length, chars, 0); return chars; } public int[][] nextIntMatrix(int rows, int cols) { int[][] matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextInt(); return matrix; } public long[][] nextLongMatrix(int rows, int cols) { long[][] matrix = new long[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextLong(); return matrix; } public char[][] nextCharMap(int rows, int cols) { char[][] matrix = new char[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextChar(); return matrix; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; /* * And now I wonder if I should delete these comments cause they might throw me off. * Lol who cares though? */ public class R364C { public static void main(String[] args) throws NumberFormatException, IOException { Scanner s = new Scanner(System.in); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(f.readLine()); char[] a = f.readLine().toCharArray(); int difTypes = 0; TreeSet<Character> types = new TreeSet<Character>(); for(int i = 0; i < n; i++) { if(!types.contains(a[i])) { types.add(a[i]); } } int i = 0, j = 0; difTypes = types.size(); int curTypes = 0; int min = Integer.MAX_VALUE; TreeSet<Character> has = new TreeSet<Character>(); HashMap<Character, Integer> freq = new HashMap<Character, Integer>(); while(i < n && j < n) { // System.out.println(i + " " + j); has.add(a[j]); if(!freq.containsKey(a[j])) { freq.put(a[j], 1); } else { freq.put(a[j], freq.get(a[j])+1); } j++; curTypes = has.size(); if(curTypes == difTypes) min = Math.min(min, j-i); // System.out.println(freq.toString()); // System.out.println(curTypes); // System.out.println(); while(i < n && has.size() == difTypes) { int Freq = freq.get(a[i]); // System.out.println(Freq); if(Freq - 1 == 0) { has.remove(a[i]); freq.put(a[i], freq.get(a[i])-1); i++; break; } freq.put(a[i], freq.get(a[i])-1); i++; if(curTypes == difTypes) min = Math.min(min, j-i); } curTypes = has.size(); } // if(curTypes == difTypes) min = Math.min(min, j-i); System.out.println(min); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class Third{ static long mod=1000000007; public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); //int t=in.readInt(); //while(t-->0) //{ int n=in.readInt(); //long n=in.readLong(); /*int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=in.readInt(); }*/ String a=in.readString(); char c[]=a.toCharArray(); HashSet<Character>ht=new HashSet<Character>(); Deque<Character>q=new LinkedList<Character>(); HashSet<Character>hs=new HashSet<Character>(); HashMap<Character,Integer>hm=new HashMap<Character,Integer>(); for(int i=0;i<n;i++) { ht.add(c[i]); } int t=ht.size(); q.addLast(c[0]); hs.add(c[0]); hm.put(c[0],1); int ans=Integer.MAX_VALUE; if(hs.size()==t) { ans=min(ans,q.size()); } for(int i=1;i<n;i++) { q.addLast(c[i]); hs.add(c[i]); if(hm.containsKey(c[i])) { int x=hm.get(c[i]); hm.put(c[i],x+1); } else hm.put(c[i],1); while(hs.size()==t) { ans=min(ans,q.size()); char ch=q.peekFirst(); int x=hm.get(ch); if(x==1) break; else { hm.put(ch, x-1); q.pollFirst(); } } } pw.println(ans); //} pw.close(); } public static long gcd(long x,long y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int abs(int a,int b) { return (int)Math.abs(a-b); } public static long abs(long a,long b) { return (long)Math.abs(a-b); } public static int max(int a,int b) { if(a>b) return a; else return b; } public static int min(int a,int b) { if(a>b) return b; else return a; } public static long max(long a,long b) { if(a>b) return a; else return b; } public static long min(long a,long b) { if(a>b) return b; else return a; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Pair implements Comparable<Pair> { int a,b; Pair (int a,int b) { this.a=a; this.b=b; } public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.a!=o.a) return Integer.compare(this.a,o.a); else return Integer.compare(this.b, o.b); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } static long sort(int a[]) { int n=a.length; int b[]=new int[n]; return mergeSort(a,b,0,n-1);} static long mergeSort(int a[],int b[],long left,long right) { long c=0;if(left<right) { long mid=left+(right-left)/2; c= mergeSort(a,b,left,mid); c+=mergeSort(a,b,mid+1,right); c+=merge(a,b,left,mid+1,right); } return c; } static long merge(int a[],int b[],long left,long mid,long right) {long c=0;int i=(int)left;int j=(int)mid; int k=(int)left; while(i<=(int)mid-1&&j<=(int)right) { if(a[i]<=a[j]) {b[k++]=a[i++]; } else { b[k++]=a[j++];c+=mid-i;}} while (i <= (int)mid - 1) b[k++] = a[i++]; while (j <= (int)right) b[k++] = a[j++]; for (i=(int)left; i <= (int)right; i++) a[i] = b[i]; return c; } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //StringBuilder sb=new StringBuilder(""); //InputReader in = new InputReader(System.in); //PrintWriter pw=new PrintWriter(System.out); //String line=br.readLine().trim(); //int t=Integer.parseInt(br.readLine()); // while(t-->0) //{ //int n=Integer.parseInt(br.readLine()); //long n=Long.parseLong(br.readLine()); //String l[]=br.readLine().split(" "); //int m=Integer.parseInt(l[0]); //int k=Integer.parseInt(l[1]); //String l[]=br.readLine().split(" "); //l=br.readLine().split(" "); /*int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(l[i]); }*/ //System.out.println(" "); //} }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C364 { static HashMap<Character, Integer> freq; static int unique = 0; public static void main(String[] args) throws Exception { FastScanner in = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); char[] s = in.next().toCharArray(); freq = new HashMap<Character, Integer>(); for(int i = 0; i < n; i++) { char c = s[i]; if(!freq.containsKey(c)) freq.put(c, 0); } int k = freq.size(); int l = 0, r = 0, best = n; inc(s[0]); while(r < n) { if(unique == k) { // got all, move left best = Math.min(best, r+1-l); dec(s[l++]); } else { // advance r if(++r == n) break; inc(s[r]); } } pw.println(best); pw.flush(); pw.close(); } static void inc(char c) { int cur = freq.get(c); if(cur == 0) unique++; freq.put(c, cur+1); } static void dec(char c) { int cur = freq.get(c); if(cur == 1) unique--; freq.put(c, cur-1); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } String next() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class C { InputStream is; int __t__ = 1; int __f__ = 0; int __FILE_DEBUG_FLAG__ = __f__; String __DEBUG_FILE_NAME__ = "src/C4"; FastScanner in; PrintWriter out; int charToIndex(char c) { if (Character.isLowerCase(c)) return c - 'a'; else if (Character.isUpperCase(c)) return c - 'A' + 26; return -1; } int CH_NUM = 52; public void solve() { int n = in.nextInt(); String s = in.next(); boolean[] exist = new boolean[CH_NUM]; int typeNum = 0; for (int i = 0; i < n; i++) { int idx = charToIndex(s.charAt(i)); if (!exist[idx]) { exist[idx] = true; typeNum++; } } int get = 0; int tail = 0, head = 0; int res = Integer.MAX_VALUE; int[] cnt = new int[CH_NUM]; while (tail < n || head < n) { if (head == n || typeNum == get) { int idx = charToIndex(s.charAt(tail++)); if (cnt[idx] == 1) get--; cnt[idx]--; } else { int idx = charToIndex(s.charAt(head++)); if (cnt[idx] == 0) get++; cnt[idx]++; } if (typeNum == get) res = Math.min(res, head - tail); } System.out.println(res); /* int[] currentRightMost = new int[CH_NUM]; Arrays.fill(currentRightMost, -1); int[][] next = new int[n+1][CH_NUM]; for (int i = 0; i < n + 1; i++) { Arrays.fill(next[i], 1 << 30); } for (int i = 0; i < n; i++) { int idx = charToIndex(s.charAt(i)); for (int j = 0; j < CH_NUM; j++) if (exist[j]) { if (currentRightMost[j] != -1) next[currentRightMost[j]][idx] = Math.min(next[currentRightMost[j]][idx], i); } currentRightMost[idx] = i; } int res = Integer.MAX_VALUE; for (int leftMost = 0; leftMost < n; leftMost++) { int maxRightMost = 0; int idx = charToIndex(s.charAt(leftMost)); for (int j = 0; j < CH_NUM; j++) if (exist[j]) { if (j != idx) maxRightMost = Math.max(maxRightMost, next[leftMost][j]); } res = Math.min(res, maxRightMost - leftMost + 1); } System.out.println(res); */ } public void run() { if (__FILE_DEBUG_FLAG__ == __t__) { try { is = new FileInputStream(__DEBUG_FILE_NAME__); } catch (FileNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } System.out.println("FILE_INPUT!"); } else { is = System.in; } in = new FastScanner(is); out = new PrintWriter(System.out); solve(); } public static void main(String[] args) { new C().run(); } public void mapDebug(int[][] a) { System.out.println("--------map display---------"); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.printf("%3d ", a[i][j]); } System.out.println(); } System.out.println("----------------------------"); System.out.println(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { return nextIntArray(n, 0); } int[] nextIntArray(int n, int margin) { int[] array = new int[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextInt(); return array; } int[][] nextIntMap(int n, int m) { int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextIntArray(m); } return map; } long nextLong() { return Long.parseLong(next()); } long[] nextLongArray(int n) { return nextLongArray(n, 0); } long[] nextLongArray(int n, int margin) { long[] array = new long[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextLong(); return array; } long[][] nextLongMap(int n, int m) { long[][] map = new long[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextLongArray(m); } return map; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { return nextDoubleArray(n, 0); } double[] nextDoubleArray(int n, int margin) { double[] array = new double[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextDouble(); return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextDoubleArray(m); } return map; } String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
linear
701_C. They Are Everywhere
CODEFORCES
/** * Created by Omar on 7/22/2016. */ import java.util.*; import java.io.*; public class CF364C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n=Integer.parseInt(br.readLine()); String input=br.readLine(); Set<Character> set = new HashSet<Character>(); for(int i=0;i<input.length();i++){ set.add(input.charAt(i)); } StringBuilder sb= new StringBuilder(); for(char x:set){ sb.append(x); } String substring1=sb.toString(); // //System.out.println(substring1); // int[] count= new int[52]; // int[] b= new int[52]; // // char k; // for(int i=0;i<substring1.length();i++){ // k=substring1.charAt(i); // //System.out.println((int)'a'); // count[(k-'A')]++; // // } // for(int i=0;i<52;i++){ // b[i]=count[i]; // // //System.out.println("count "+count[i]); // } // int answer=set.size(); // // // for(int i=0;i<input.length();i++){ // // } // System.out.println(answer); // //System.out.println("WAIT"); System.out.println(solve(input,substring1).length()); pw.close(); br.close(); } public static boolean isEmpty(int[] a){ for(int i=0;i<a.length;i++){ if(a[i]!=0){ return false; } } return true; } public static String solve(String S, String T) { HashMap<Character, Integer> D = new HashMap<>(); HashMap<Character, Integer> GET = new HashMap<>(); int B,E; for (int i=0; i<T.length();i++) { char c=T.charAt(i); if (!D.containsKey(c)) { D.put(c, 1); } else { D.put(c, D.get(c) + 1); } } int ccc = 0; B=0; E=0; int min = Integer.MAX_VALUE; // int max = Integer.MIN_VALUE; String RESULT = ""; while (E < S.length()) { char c = S.charAt(E); if (D.containsKey(c)) { if (GET.containsKey(c)) { if (GET.get(c) < D.get(c)) ccc++; //ccc-- GET.put(c, GET.get(c) + 1); } else { GET.put(c, 1); ccc++; //ccc-- } } if (ccc == T.length()) { // if (ccc != B.length()) { char test = S.charAt(B); while (!GET.containsKey(test) || GET.get(test) > D.get(test)) { if (GET.containsKey(test) && GET.get(test) > D.get(test)) // GET.put(test, GET.get(test) - 24); GET.put(test, GET.get(test) - 1); //B-=B; B++; test = S.charAt(B); //test += S.charAt(B); } if (E - B + 1 < min) { RESULT = S.substring(B, E + 1); min = E - B + 1; } //} } E++; } //if(E==0) return RESULT; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; /** * @author Ran Bi ([email protected]) */ public class C { public static void main(String[] arg) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.valueOf(in.readLine()); char[] s = in.readLine().toCharArray(); int i = 0, j = 0; int[] ct = new int[256]; Set<Character> all = new HashSet<>(); for (char c : s) { all.add(c); } int total = 0, res = Integer.MAX_VALUE; while (j < s.length) { while (total < all.size() && j < s.length) { if (ct[s[j]] == 0) { total++; } ct[s[j]]++; j++; } res = Math.min(res, j - i); while (total == all.size() && i < s.length) { ct[s[i]]--; if (ct[s[i]] == 0) { total--; } i++; if (total == all.size()) { res = Math.min(res, j - i); } } } System.out.println(res); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public final class round_364_c { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws Exception { int n=sc.nextInt();char[] arr=sc.next().toCharArray();int[] sum=new int[123];int[][] pre=new int[123][n+1]; char[] a=new char[n+1]; for(int i=1;i<=n;i++) { a[i]=arr[i-1]; } boolean[] v=new boolean[123]; for(int i=1;i<=n;i++) { sum[a[i]]++;v[a[i]]=true; for(int j=65;j<=90;j++) { pre[j][i]=sum[j]; } for(int j=97;j<=122;j++) { pre[j][i]=sum[j]; } } long min=Integer.MAX_VALUE; for(int i=1;i<=n;i++) { int low=0,high=n-i+1;boolean got=false; while(low<high) { int mid=(low+high)>>1; boolean curr=true; for(int j=65;j<=90;j++) { if(v[j]) { if(pre[j][i+mid]-pre[j][i-1]<=0) { curr=false; break; } } } for(int j=97;j<=122;j++) { if(v[j]) { if(pre[j][i+mid]-pre[j][i-1]<=0) { curr=false; break; } } } if(curr) { got=true; high=mid; } else { low=mid+1; } } if(got) { min=Math.min(min,(i+low)-i+1); } } out.println(min); out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.awt.Point; import java.io.*; import java.lang.Integer; import java.math.BigInteger; import java.util.*; public class Main { final boolean ONLINE_JUDGE = !new File("input.txt").exists(); BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Main().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class LOL implements Comparable<LOL> { int x; int y; public LOL(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(LOL o) { if (o.x != x) return (int) (o.x - x); // ----> return (int) (y - o.y); // <---- } } long modulo = 1000 * 1000 * 1000 + 7; long binPow (long a, long b) { if(b == 0) return 1; long c = binPow(a, b / 2); long ans = (c * c) % modulo; if(b % 2 == 1) ans = (ans * a) % modulo; return ans; } int[] gcd (int a, int b) { int[] res = new int[3]; if (a == 0) { res[0] = b; res[1] = 0; res[2] = -1; return res; } res = gcd (b%a, a); int x = -(res[2] + (b / a) * res[1]); int y = - res[1]; res[1] = x; res[2] = y; return res; } public void solve() throws IOException { int n = readInt(); HashMap<Character,Integer> mapa = new HashMap<>(); char[] s = readString().toCharArray(); for(int i = 0; i < n; i++) { if(mapa.containsKey(s[i])) { int x = mapa.get(s[i]); mapa.replace(s[i], x + 1); } else mapa.put(s[i], 1); } int sz = mapa.size(); mapa = new HashMap<>(); int i = 0; while (mapa.size() < sz) { if(mapa.containsKey(s[i])) { int x = mapa.get(s[i]); mapa.replace(s[i], x + 1); } else mapa.put(s[i], 1); i++; } int ans = i; int left = 0; int right = i - 1; while(right < n) { while(left < right) { int y = mapa.get(s[left]); if(y == 1) mapa.remove(s[left]); else mapa.replace(s[left], y - 1); if(mapa.size() == sz) { ans = Math.min(ans, right - left); left++; } else { left++; break; } } right++; if(right < n) { if (mapa.containsKey(s[right])) { int x = mapa.get(s[right]); mapa.replace(s[right], x + 1); } else mapa.put(s[right], 1); } } out.print(ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class C364C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; static int n; static int[] a; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); n = nextInt(); int ans = n, cc, cur = 0; a = new int [52]; char[] c = next().toCharArray(); int l = 0, len = 0; for (int i = 0; i < n; ++i) { if (Character.isUpperCase(c[i])) { cur = 26 + c[i] - 'A'; } else cur = c[i] - 'a'; if (a[cur] == 0) { a[cur]++; len++; ans = i - l + 1; } else { a[cur]++; for (; l < i; ++l) { if (Character.isUpperCase(c[l])) { cc = 26 + c[l] - 'A'; } else cc = c[l] - 'a'; if (a[cc] > 1) { --a[cc]; } else break; } if (i - l + 1 < ans) { ans = i - l + 1; } } } /*int l = 0, r = n - 1; for (l = 0; l < n; ++l) { if (Character.isUpperCase(c[l])) { if (a[26 + c[l] - 'A'] > 1) { a[26 + c[l] - 'A']--; } else break; } else { if (a[c[l] - 'a'] > 1) { a[c[l] - 'a']--; } else break; } } for (r = n - 1; r >= 0; --r) { if (Character.isUpperCase(c[r])) { if (a[26 + c[r] - 'A'] > 1) { a[26 + c[r] - 'A']--; } else break; } else { if (a[c[r] - 'a'] > 1) { a[c[r] - 'a']--; } else break; } }*/ pw.print(ans); pw.close(); } private static int sumf(int[] fen, int id) { int summ = 0; for (; id >= 0; id = (id & (id + 1)) - 1) summ += fen[id]; return summ; } private static void addf(int[] fen, int id) { for (; id < fen.length; id |= id + 1) fen[id]++; } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
linear
701_C. They Are Everywhere
CODEFORCES
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class A { static double eps=(double)1e-15; static long mod=(int)1e9+7; public static void main(String args[]){ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code---------- int n=in.nextInt(); int l=0,r=0; String s=in.nextLine(); HashSet<Character> size=new HashSet<>(); for(int i=0;i<n;i++){ char p=s.charAt(i); size.add(p); } int chk=size.size(); HashMap<Character, Integer> hm=new HashMap<>(); int ans=Integer.MAX_VALUE; while(l<n){ if(hm.size()<chk && r<n){ char p=s.charAt(r); if(hm.containsKey(p)){ hm.put(p, hm.get(p)+1); } else{ hm.put(p, 1); } r++; } else{ char p=s.charAt(l); if(hm.get(p)==1){ hm.remove(p); } else{ hm.put(p, hm.get(p)-1); } l++; } if(hm.size()==chk){ ans=Math.min(ans, r-l); } } out.println(ans); out.close(); //---------------The End------------------ } static class Pair implements Comparable<Pair> { int u; int v; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedInputStream; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner in=new Scanner(new BufferedInputStream(System.in)); int n=in.nextInt(); char b[]=in.next().toCharArray(); int bb[]=new int [b.length]; int Mark[]=new int [26*2+1]; int Mark1[]=new int [26*2+1]; int ans=0; for(int i=0;i<b.length;i++){ char f=b[i]; int a; if(f>='a'&&f<='z') a=f-'a'; else a=f-'A'+26; bb[i]=a; if(Mark1[a] == 0){ ans++; Mark1[a]=1;} } // System.out.println(ans); int i; // int L ,R ,nowsum ,Ans; int L = 0 ,nowsum = 0 ,Ans = n,R = 0; //找到LR for(i = 0 ;i < n ;i ++) { if(Mark[bb[i]]==0) nowsum ++; Mark[bb[i]] ++; if(nowsum == ans) { R = i; break; } } // System.out.println("r"+R); Ans = R - L + 1; for(i = L ;i < n ;i ++) { if((--Mark[bb[i]])==0) { int ok = 0; for(int j = R + 1 ;j < n ;j ++) { Mark[bb[j]] ++; if(bb[j] == bb[i]) { ok = 1; R = j; break; } } if(ok==0) break; } if(Ans > R - i) Ans = R - i; } System.out.println(Ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
//package baobab; import java.io.*; import java.util.*; public class C { public static void main(String[] args) { CIO io = new CIO(); try { Csolver solver = new Csolver(io); solver.solve(); } finally { io.close(); } } } class Csolver { CIO io; public Csolver(CIO io) { this.io = io; } public void solve() { int n = io.nextInt(); String input = io.next(); int[] count = new int[1000]; int pokemonsInRange = 0; int answer = Integer.MAX_VALUE; int a = 0; int b = 0; for (; b < n ; b++) { char end = input.charAt(b); if (count[end] == 0) { pokemonsInRange++; answer = Integer.MAX_VALUE; } count[end]++; while (count[input.charAt(a)] > 1) { count[input.charAt(a)]--; a++; } answer = Math.min(answer, b-a+1); } io.println(answer); } private static class Pair implements Comparable<Pair> { int id; long val; public Pair(long val, int id) { this.val = val; this.id = id; } @Override public int compareTo(Pair o) { if (this.val < o.val) return -1; if (this.val > o.val) return 1; return this.id - o.id; } } private List<Integer>[] toGraph(CIO io, int n) { List<Integer>[] g = new ArrayList[n+1]; for (int i=1; i<=n; i++) g[i] = new ArrayList<>(); for (int i=1; i<=n-1; i++) { int a = io.nextInt(); int b = io.nextInt(); g[a].add(b); g[b].add(a); } return g; } } class CIO extends PrintWriter { private InputStreamReader r; private static final int BUFSIZE = 1 << 15; private char[] buf; private int bufc; private int bufi; private StringBuilder sb; public CIO() { super(new BufferedOutputStream(System.out)); r = new InputStreamReader(System.in); buf = new char[BUFSIZE]; bufc = 0; bufi = 0; sb = new StringBuilder(); } private void fillBuf() throws IOException { bufi = 0; bufc = 0; while(bufc == 0) { bufc = r.read(buf, 0, BUFSIZE); if(bufc == -1) { bufc = 0; return; } } } private boolean pumpBuf() throws IOException { if(bufi == bufc) { fillBuf(); } return bufc != 0; } private boolean isDelimiter(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; } private void eatDelimiters() throws IOException { while(true) { if(bufi == bufc) { fillBuf(); if(bufc == 0) throw new RuntimeException("IO: Out of input."); } if(!isDelimiter(buf[bufi])) break; ++bufi; } } public String next() { try { sb.setLength(0); eatDelimiters(); int start = bufi; while(true) { if(bufi == bufc) { sb.append(buf, start, bufi - start); fillBuf(); start = 0; if(bufc == 0) break; } if(isDelimiter(buf[bufi])) break; ++bufi; } sb.append(buf, start, bufi - start); return sb.toString(); } catch(IOException e) { throw new RuntimeException("IO.next: Caught IOException."); } } public int nextInt() { try { int ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextInt: Invalid int."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int."); ret *= 10; ret -= (int)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int."); } else { throw new RuntimeException("IO.nextInt: Invalid int."); } ++bufi; } if(positive) { if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextInt: Caught IOException."); } } public long nextLong() { try { long ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextLong: Invalid long."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long."); ret *= 10; ret -= (long)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long."); } else { throw new RuntimeException("IO.nextLong: Invalid long."); } ++bufi; } if(positive) { if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextLong: Caught IOException."); } } public double nextDouble() { return Double.parseDouble(next()); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; public class theyareeverywhere { public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); //SWEEP LINE BABYY int n = Integer.parseInt(r.readLine()); char[] pokemans = r.readLine().toCharArray(); int[] counts = new int[52]; boolean[] exists = new boolean[52]; for (int i = 0; i < pokemans.length; i++) { exists[index(pokemans[i])] = true; } int left = 0, right = 0; counts[index(pokemans[0])] = 1; int answer = 1000000000; while (left < n && right < n) { if (!valid(counts, exists)) { //move right right++; if (right < n) counts[index(pokemans[right])]++; } else { answer = Math.min(answer, right - left + 1); left++; if (left - 1 >= 0) counts[index(pokemans[left - 1])]--; } } w.println(answer); w.flush(); } public static boolean valid(int[] counts, boolean[] exists) { for (int i = 0; i < counts.length; i++) { if (exists[i] && counts[i] == 0) return false; } return true; } public static int index(char c) { if (c >= 'a' && c <= 'z') { return c - 'a'; } else { return c - 'A' + 26; } } }
linear
701_C. They Are Everywhere
CODEFORCES
/** * Created by ankeet on 7/22/16. */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C701 { static FastReader in = null; static PrintWriter out = null; public static void solve() { int n = in.nint(); String pk = in.next(); boolean[] occ = new boolean[52]; for(int i=0; i<n; i++) { char c = pk.charAt(i); int val = Character.isUpperCase(c)? (int)(c-'A') : (int)(c-'a'+26); occ[val] = true; } int[][] next = new int[n][52]; for(int i=0; i<n; i++) for(int j=0; j<52; j++) next[i][j] = -1; for(int i= n-1; i>=0; i--) { char c = pk.charAt(i); int val = Character.isUpperCase(c)? (int)(c-'A') : (int)(c-'a'+26); next[i][val] = i; if(i<n-1) for(int j=0; j<52; j++) { if(j!=val) { next[i][j] = next[i+1][j]; } } } int min = Integer.MAX_VALUE; for(int i=0; i<n; i++) { int maxd = 0; boolean endearly = false; for(int j=0; j<52; j++) { if(occ[j] && next[i][j] == -1) { endearly = true; break; } else if(occ[j]) { maxd = Math.max(maxd, next[i][j]-i+1); } } if(endearly) break; min = Math.min(min, maxd); } out.println(min); } public static void main(String[] args) { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } static class FastReader { BufferedReader read; StringTokenizer tokenizer; public FastReader(InputStream in) { read = new BufferedReader(new InputStreamReader(in)); } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(read.readLine()); }catch(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nint() { return Integer.parseInt(next()); } public long nlong() { return Long.parseLong(next()); } public double ndouble() { return Double.parseDouble(next()); } public int[] narr(int n) { int[] a = new int[n]; for(int i=0; i<n; ++i) { a[i] = nint(); } return a; } public long[] nlarr(int n) { long[] a = new long[n]; for(int i=0; i<n; ++i) { a[i] = nlong(); } return a; } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.InputMismatchException; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final double PI = Math.PI; private final int INF = (int)(1e9); private final double EPS = 1e-6; private final int SIZEN = (int)(1e7); private final int MOD = (int)(1e9 + 7); private final long MODH = 10000000007L, BASE = 10007; private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0}; int n; int[] sum; int[][] a; public void foo1() { int n = scan.nextInt(); int sum = 0; int[] a = new int[n]; for (int i = 0;i < n;++i) { a[i] = scan.nextInt(); sum += a[i]; } int avg = sum * 2 / n; for (int i = 0;i < n;++i) { if (a[i] == 0) { continue; } for (int j = i + 1;j < n;++j) { if (a[i] + a[j] == avg) { a[j] = 0; System.out.println((i + 1) + " " + (j + 1)); break; } } } } public void foo2() { int n = scan.nextInt(); int m = scan.nextInt(); HashSet<Integer> row = new HashSet<Integer>(); HashSet<Integer> col = new HashSet<Integer>(); for (int i = 0;i < m;++i) { int x = scan.nextInt(); int y = scan.nextInt(); row.add(x); col.add(y); out.print((long) (n - row.size()) * (n - col.size()) + " "); } } public int getId(char c) { return (c >= 'a' && c <= 'z') ? c - 'a': c - 'A' + 26; } public boolean isOk(int len) { for (int i = 0;i + len <= n;++i) { boolean flag = true; for (int j = 0;j < 52;++j) { if (a[i + len][j] - a[i][j] == 0 && sum[j] != 0) { flag = false; break; } } if (flag) { return true; } } return false; } public void foo() { n = scan.nextInt(); char[] s = scan.next().toCharArray(); a = new int[n + 1][52]; sum = new int[52]; for (int i = 0;i < n;++i) { for (int j = 0;j < 52;++j) a[i + 1][j] = a[i][j]; ++a[i + 1][getId(s[i])]; ++sum[getId(s[i])]; } int left = 1, right = n, ans = n; while (left <= right) { int mid = (left + right) >> 1; if (isOk(mid)) { ans = mid; right = mid - 1; } else { left = mid + 1; } } out.println(ans); } public static void main(String[] args) { Main m = new Main(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * 1---Get greatest common divisor * @param a : first number * @param b : second number * @return greatest common divisor */ public long gcd(long a, long b) { return 0 == b ? a : gcd(b, a % b); } /** * 2---Get the distance from a point to a line * @param x1 the x coordinate of one endpoint of the line * @param y1 the y coordinate of one endpoint of the line * @param x2 the x coordinate of the other endpoint of the line * @param y2 the y coordinate of the other endpoint of the line * @param x the x coordinate of the point * @param y the x coordinate of the point * @return the distance from a point to a line */ public double getDist(long x1, long y1, long x2, long y2, long x, long y) { long a = y2 - y1; long b = x1 - x2; long c = y1 * (x2 - x1) - x1 * (y2 - y1); return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); } /** * 3---Get the distance from one point to a segment (not a line) * @param x1 the x coordinate of one endpoint of the segment * @param y1 the y coordinate of one endpoint of the segment * @param x2 the x coordinate of the other endpoint of the segment * @param y2 the y coordinate of the other endpoint of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return the distance from one point to a segment (not a line) */ public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y) { double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1); if(cross <= 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); if(cross >= d) { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } double r = cross / d; double px = x1 + (x2 - x1) * r; double py = y1 + (y2 - y1) * r; return (x - px) * (x - px) + (y - py) * (y - py); } /** * 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * @param t: String to match. * @param p: String to be matched. * @return if can match, first index; otherwise -1. */ public int kmpMatch(char[] t, char[] p) { int n = t.length; int m = p.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && p[i] != p[j + 1]) { j = next[j]; } if(p[i] == p[j + 1]) { ++j; } next[i] = j; } j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && t[i] != p[j + 1]) { j = next[j]; } if(t[i] == p[j + 1]) { ++j; } if(j == m - 1) { return i - m + 1; } } return -1; } /** * 5---Get the hash code of a String * @param s: input string * @return hash code */ public long hash(String s) { long key = 0, t = 1; for(int i = 0;i < s.length();++i) { key = (key + s.charAt(i) * t) % MODH; t = t * BASE % MODH; } return key; } /** * 6---Get x ^ n % MOD quickly. * @param x: base * @param n: times * @return x ^ n % MOD */ public long quickMod(long x, long n) { long ans = 1; while(n > 0) { if(1 == n % 2) { ans = ans * x % MOD; } x = x * x % MOD; n >>= 1; } return ans; } /** * 7---judge if a point is located inside a polygon * @param x0 the x coordinate of the point * @param y0 the y coordinate of the point * @return true if it is inside the polygon, otherwise false */ /*public boolean contains(double x0, double y0) { int cross = 0; for(int i = 0;i < n;++i) { double s = x[i + 1] == x[i] ? 100000000 : (double)(y[i + 1] - y[i]) / (x[i + 1] - x[i]); boolean b1 = x[i] <= x0 && x0 < x[i + 1]; boolean b2 = x[i + 1] <= x0 && x0 < x[i]; boolean b3 = y0 < s * (x0 - x[i]) + y[i]; if((b1 || b2) && b3) ++cross; } return cross % 2 != 0; }*/ /** * 8---judge if a point is located on the segment * @param x1 the x coordinate of one point of the segment * @param y1 the y coordinate of one point of the segment * @param x2 the x coordinate of another point of the segment * @param y2 the y coordinate of another point of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return true if it is located on the segment, otherwise false */ public boolean isOnSeg(long x1, long y1, long x2, long y2, long x, long y) { return (x - x1) * (y2 - y1) == (x2 - x1) * (y - y1) && x >= Math.min(x1, x2) && x <= Math.max(x1, x2) && y >= Math.min(y1, y2) && y <= Math.max(y1, y2); } /** * 9---get the cross product * @param p1 point A * @param p2 point B * @param p point O * @return cross product of OA x OB */ /*public long cross(Point p1, Point p2, Point p) { return (long)(p1.x - p.x) * (p2.y - p.y) - (long)(p2.x - p.x) * (p1.y - p.y); }*/ /** * 10---implement topsort and tell if it is possible * @return true if it is possible to implement topsort, otherwise false */ /*public boolean topsort() { Queue<Integer> q = new LinkedList<Integer>(); StringBuilder ans = new StringBuilder(); int[] in = new int[26]; for(int i = 0;i < 26;++i) { if(0 == in[i]) { ans.append((char)('a' + i)); q.add(i); } } while(!q.isEmpty()) { int u = q.poll(); for(int i = 0;i < 26;++i) { if(map[u][i]) { --in[i]; if(0 == in[i]) { ans.append((char)('a' + i)); q.add(i); } } } } return 26 == ans.length(); }*/ class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c & 15; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c & 15) * m; c = read(); } } return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.math.*; public class main { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter pw = new PrintWriter(System.out); public static String line; public static StringTokenizer st; public static ArrayList<ArrayList<Integer>> adjList; public static int[] dr = {-1, 0, 1, 0, -1, 1, 1, -1}; public static int[] dc = {0, 1, 0, -1, 1, 1, -1, -1}; public static void main(String[] args) throws Exception{ int N = Integer.parseInt(br.readLine()); char[] A = br.readLine().toCharArray(); HashSet<Character> cndD = new HashSet<Character>(); for(int i = 0; i < N; i++){ cndD.add(A[i]); } int cnt = cndD.size(); int a = 0; int b = 0; int ans = (1 << 30); HashMap<Character, Integer> d = new HashMap<Character, Integer>(); while(b < N){ if(d.containsKey(A[b])){ if(A[a] == A[b]){ a++; while(d.get(A[a]) > 1){ d.put(A[a], d.get(A[a])-1); a++; } } else{ d.put(A[b], d.get(A[b])+1); } } else{ d.put(A[b], 1); } if(d.size() == cnt){ ans = Math.min(b-a+1, ans); } b++; } pw.print(ans + "\n"); pw.close(); br.close(); } } class Pair implements Comparable<Pair>{ public int a, b; Pair(int a, int b){ this.a = a; this.b = b; } @Override public int compareTo(Pair P){ if(P.b != this.b){ return b - P.b; } else if(P.a == this.a){ return a - P.a; } else{ return 0; } } public String toString(){ return a + " " + b; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); char[] poks = in.next().toCharArray(); boolean[] was = new boolean[52]; for (int i = 0; i < n; i++) { if (Character.isLowerCase(poks[i])) { was[poks[i] - 'a'] = true; } else { was[poks[i] - 'A' + 26] = true; } } int count = 0; for (int i = 0; i < 52; i++) { count += was[i] ? 1 : 0; } int[] vis = new int[52]; int pre = 0; int chr = 0; int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int pos = poks[i] - 'a'; if (Character.isUpperCase(poks[i])) { pos = poks[i] - 'A' + 26; } if (vis[pos] == 0) { chr++; } vis[pos]++; while (chr == count) { ans = Math.min(ans, i - pre + 1); pos = poks[pre] - 'a'; if (Character.isUpperCase(poks[pre])) { pos = poks[pre] - 'A' + 26; } vis[pos]--; if (vis[pos] == 0) chr--; pre++; } } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Created by pallavi on 22/7/16. */ public class C701 { public static int f(char c) { if (c >= 'a' && c <= 'z') { return c - 'a'; } else { return 26 + c - 'A'; } } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); char[] ch = reader.readLine().toCharArray(); LinkedList<Integer>[] p = new LinkedList[52]; for (int i = 0; i < 52; i++) { p[i] = new LinkedList<>(); } int[] fc = new int[n]; for (int i = 0; i < n; i++) { int cc = f(ch[i]); p[cc].add(i); fc[i] = cc; } int en = 0; for (int i = 0; i < 52; i++) { if (p[i].size() > 0) en = Math.max(en, p[i].poll()); } int mx = en + 1; for (int i = 0; i < n; i++) { if (p[fc[i]].size() == 0) break; en = Math.max(en, p[fc[i]].poll()); mx = Math.min(mx, en - i); } System.out.println(mx); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); char[]a = next().toCharArray(); int[]cnt = new int[256]; for (int i = 0; i < n; i++) { cnt[a[i]]++; } int alldiff = 0; for (int i = 0; i < 256; i++) { if (cnt[i] > 0) alldiff++; } Arrays.fill(cnt, 0); int diff = 0, right = -1, ans = n+5; for (int i = 0; i < n; i++) { if (right < i) { cnt[a[i]]++; diff = 1; right = i; } while (right < n-1 && diff < alldiff) { right++; cnt[a[right]]++; if (cnt[a[right]]==1) diff++; } if (diff==alldiff && right-i+1 < ans) { ans = right-i+1; } cnt[a[i]]--; if (cnt[a[i]]==0) diff--; } System.out.println(ans); pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { FastScanner in; PrintWriter out; static final String FILE = ""; public void solve() { int n = in.nextInt(); TreeMap<Character, Integer> map = new TreeMap<>(); ArrayList<Integer> list = new ArrayList<>(); String s = in.next(); for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (!map.containsKey(ch)) map.put(ch, map.size()); list.add(map.get(ch)); } int l = 0; int ans = Integer.MAX_VALUE; int nad = map.size(); int cnt[] = new int[n]; for (int i = 0; i < list.size(); i++) { if (cnt[list.get(i)] == 0) nad--; cnt[list.get(i)]++; if (nad == 0) { ans = min(ans, i - l + 1); while (true) { if (cnt[list.get(l)] == 1) { ans = min(ans, i - l + 1); cnt[list.get(l)]--; l++; nad++; break; } else { cnt[list.get(l)]--; l++; } } } } out.print(ans); } public void run() { if (FILE.equals("")) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { try { in = new FastScanner(new FileInputStream(FILE + ".in")); out = new PrintWriter(new FileOutputStream(FILE + ".out")); } catch (FileNotFoundException e) { e.printStackTrace(); } } solve(); out.close(); } public static void main(String[] args) { (new Main()).run(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> { public A a; public B b; public Pair(A a, B b) { this.a = a; this.b = b; } @Override public int compareTo(Pair<A, B> o) { if (o == null || o.getClass() != getClass()) return 1; int cmp = a.compareTo(o.a); if (cmp == 0) return b.compareTo(o.b); return cmp; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (a != null ? !a.equals(pair.a) : pair.a != null) return false; return !(b != null ? !b.equals(pair.b) : pair.b != null); } } class PairInt extends Pair<Integer, Integer> { public PairInt(Integer u, Integer v) { super(u, v); } } class PairLong extends Pair<Long, Long> { public PairLong(Long u, Long v) { super(u, v); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeSet; public class TheyAreEverywhere { static StringTokenizer st; static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in), 325678); static int[] id = new int[100000]; public static void main(String[] args) throws IOException { int n = in(); String s = next(); int total = 0; int[] seq = new int[n]; boolean[] c = new boolean[100000]; for (int i = 0; i < n; i++) { seq[i] = s.charAt(i); if (!c[seq[i]]) { total++; c[seq[i]] = true; } } Arrays.fill(id, -1); int best = Integer.MAX_VALUE; TreeSet<Integer> q = new TreeSet<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return id[o1] - id[o2]; } }); for (int i = 0; i < n; i++) { q.remove(seq[i]); id[seq[i]] = i; q.add(seq[i]); if (q.size() == total) { //System.out.println("best: i=" + i + " id=" + id[q.first()]); best = Math.min(best, i - id[q.first()] + 1); } //System.out.println("i="+i+" " +q.toString()); } System.out.println(best); } public static int in() throws IOException { return Integer.parseInt(next()); } public static long inl() throws IOException { return Long.parseLong(next()); } public static String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.HashMap; import java.util.Map; public class Round364_div2_C { public static void main(String[] args) throws IOException { FastReader in = new FastReader(System.in); PrintWriter out = new PrintWriter(System.out); solve(in, out); out.flush(); } public static void solve(FastReader in, PrintWriter out) { int n = in.readInt(); String s = in.readString(); int totalCnt = (int) s.chars().distinct().count(); Map<Character, Integer> curCnts = new HashMap<>(); int solution = s.length(); int i = 0; for (int j = 0 ; j < s.length() ; j++) { // add s_j char sj = s.charAt(j); curCnts.put(sj, curCnts.getOrDefault(sj, 0) + 1); // contract s_i while (curCnts.getOrDefault(s.charAt(i), 0) > 1) { char si = s.charAt(i); int siCnt = curCnts.get(si); if (siCnt > 1) { curCnts.put(si, siCnt - 1); } else { curCnts.remove(si); } i++; } if (curCnts.size() == totalCnt) { solution = Math.min(solution, j - i + 1); } } out.println(solution); } /** * Custom buffered reader. Faster than Scanner and BufferedReader + StringTokenizer. */ static class FastReader { private final InputStream stream; private int current; private int size; private byte[] buffer = new byte[1024 * 8]; public FastReader(InputStream stream) { this.stream = stream; current = 0; size = 0; } public int readInt() { int sign = 1; int abs = 0; int c = readNonEmpty(); if (c == '-') { sign = -1; c = readAny(); } do { if (c < '0' || c > '9') { throw new IllegalStateException(); } abs = 10 * abs + (c - '0'); c = readAny(); } while (!isEmpty(c)); return sign * abs; } public int[] readIntArray(int n) { int[] array = new int[n]; for (int i = 0 ; i < n ; i++) { array[i] = readInt(); } return array; } public char readChar() { return (char) readNonEmpty(); } public String readString() { StringBuffer sb = new StringBuffer(); int c; do { c = readAny(); } while (isEmpty(c)); do { sb.append((char) c); c = readAny(); } while (!isEmpty(c)); return sb.toString(); } private int readAny() { try { if (current >= size) { current = 0; size = stream.read(buffer); if (size < 0) { return -1; } } } catch (IOException e) { throw new RuntimeException("Failed to readAny next byte", e); } return buffer[current++]; } private int readNonEmpty() { int result; do { result = readAny(); } while (isEmpty(result)); return result; } private static boolean isEmpty(int c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1; } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; import java.io.*; public class C{ public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(in, out); out.close(); } static class Solver{ public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); HashMap<Character, Integer> map = new HashMap<>(); for (int i = 0; i < n; ++ i) { map.put(s.charAt(i), 0); } int l = 0, r = 0, cnt = 0, ans = n; char c; while (l < n) { while (r < n && cnt < map.size()) { c = s.charAt(r); map.put(c, map.get(c) + 1); if (map.get(c) == 1) ++cnt; ++r; } if (cnt == map.size() && r-l < ans) ans = r-l; c = s.charAt(l); map.put(c, map.get(c)-1); if (map.get(c) == 0) --cnt; ++l; } out.println(ans); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader (InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (tokenizer == null || ! tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; public class Q3a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); String s = in.nextLine(); HashMap<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < n; i++) { Character c = s.charAt(i); int ci = (int) c.charValue(); // System.out.println(ci); seen.put(ci, seen.get(ci) == null ? 1 : seen.get(ci) + 1); } HashMap<Integer, Integer> sub = new HashMap<Integer, Integer>(); int start = 0; int min = 10000000; for (int i = 0; i < n; i++) { Character c = s.charAt(i); int ci = (int) c.charValue(); sub.put(ci, sub.get(ci) == null ? 1 : sub.get(ci) + 1); while(sub.size() == seen.size()) { min = Math.min(min, i - start + 1); c = s.charAt(start); start ++; ci = (int) c.charValue(); if( sub.get(ci) == 1) sub.remove(ci); else sub.put(ci, sub.get(ci) - 1); } } System.out.print(min); // System.out.println( seen_all_at - begin + 1); in.close(); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; public class TestClass11 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub InputReader in=new InputReader(System.in); OutputWriter out=new OutputWriter(System.out); int n=in.readInt(); String s=in.readString(); int low[]=new int[26]; int upper[]=new int[26]; boolean islow[]=new boolean[26]; boolean isupper[]=new boolean[26]; Arrays.fill(low,Integer.MAX_VALUE); Arrays.fill(upper, Integer.MAX_VALUE); int ans[]=new int[n]; int finalsans=Integer.MAX_VALUE; for(int i=0;i<n;i++){ int c=s.charAt(i); if(c>='a'&&c<='z'){ islow[c-'a']=true; } else{ isupper[c-'A']=true; } } for(int i=n-1;i>=0;i--){ int c=s.charAt(i); if(c>='a'&&c<='z'){ low[c-'a']=i; } else{ upper[c-'A']=i; } for(int j=0;j<26;j++){ if(islow[j]==true){ ans[i]=Math.max(ans[i], low[j]); } } for(int j=0;j<26;j++){ if(isupper[j]==true){ ans[i]=Math.max(ans[i], upper[j]); } } finalsans=Math.min(ans[i]-i+1, finalsans); } System.out.println(finalsans); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { File inputFile = new File("entradaC"); if (inputFile.exists()) System.setIn(new FileInputStream(inputFile)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { int n = Integer.parseInt(line); char[] p = in.readLine().toCharArray(); HashMap<Character, Integer> dif = new HashMap<>(); for (int i = 0; i < p.length; i++) dif.put(p[i], 0); int ndif = dif.size(); int head = 0, tail = 0, cnt = 0, ans = Integer.MAX_VALUE, cur; while (head < n) { cur = dif.get(p[head]); if (cur == 0) cnt++; dif.put(p[head], cur + 1); head++; if (cnt == ndif) ans = Math.min(ans, head - tail); while (tail < head && cnt == ndif) { cur = dif.get(p[tail]); if (cur == 1) cnt--; dif.put(p[tail], cur - 1); tail++; if (cnt == ndif) ans = Math.min(ans, head - tail); } } if (ndif == 1) ans = 1; out.append(ans + "\n"); } System.out.print(out); } static int[] readInts(String line) { StringTokenizer st = new StringTokenizer(line.trim()); int a[] = new int[st.countTokens()], index = 0; while (st.hasMoreTokens()) a[index++] = Integer.parseInt(st.nextToken()); return a; } static long[] readLongs(String line) { StringTokenizer st = new StringTokenizer(line.trim()); long a[] = new long[st.countTokens()]; int index = 0; while (st.hasMoreTokens()) a[index++] = Long.parseLong(st.nextToken()); return a; } static double[] readDoubles(String line) { StringTokenizer st = new StringTokenizer(line.trim()); double a[] = new double[st.countTokens()]; int index = 0; while (st.hasMoreTokens()) a[index++] = Double.parseDouble(st.nextToken()); return a; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class Round364C { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = 0; String line = sc.nextLine(); ArrayList<Character> poks = new ArrayList<Character>(); boolean ex[] = new boolean[256]; for(int i=0; i<n; i++) { if(!ex[line.charAt(i)]) { ex[line.charAt(i)] = true; poks.add(line.charAt(i)); } } int l = 0; int r = 0; int dist = 1; int occ[] = new int[256]; occ[line.charAt(0)] = 1; int min = n; while(r < n) { if(dist == poks.size()) min = Math.min(min, r - l + 1); if(l < r && dist == poks.size()) { occ[line.charAt(l)]--; if(occ[line.charAt(l)] == 0) dist--; l++; continue; } if(r < n-1){ occ[line.charAt(r+1)]++; if(occ[line.charAt(r+1)] == 1) dist++; } r++; } System.out.println(min); } static int n,k; static int dp[][][]; static class Scanner { BufferedReader br; StringTokenizer st; Scanner(FileReader f) { br = new BufferedReader(f); } public boolean ready() throws IOException { return br.ready(); } Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import com.sun.org.apache.xml.internal.utils.StringComparable; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; public class Main { public static void main(String[] args) { // Test.testing(); ConsoleIO io = new ConsoleIO(); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } ArrayList<ArrayList<Integer>> gr; boolean[] visit; class Edge { public Edge(int u, int v, int c) { this.u = u; this.v = v; this.c = c; } public int u; public int v; public int c; } long MOD = 1_000_000_007; int N, M, K; double[][] map; public void solve() { String s = io.readLine(); N = Integer.parseInt(s); char[] a = io.readLine().toCharArray(); int[] look = new int[256]; Arrays.fill(look, 10000); int k = 0; for (int i = 0; i < a.length; i++) { if (look[a[i]] == 10000) { look[a[i]] = k; k++; } } int res = N; long need = (1L << k) - 1; long mask = 0; int head = 0; int tail = 0; int[] c = new int[k]; while (head < a.length) { while (head < a.length && mask != need) { int v = look[a[head]]; if (c[v] == 0) mask |= (1L << v); c[v]++; head++; } while (tail < head && mask == need) { res = Math.min(res, head - tail); int v = look[a[tail]]; c[v]--; if (c[v] == 0) mask ^= (1L << v); tail++; } } io.writeLine(res + ""); } long gcd(long a, long b) { if (a < b) return gcd(b, a); if (b == 0) return a; return gcd(b, a % b); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long readLong() { return Long.parseLong(this.readLine()); } public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int readInt() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public void writeIntArray(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) {if (i > 0) sb.append(' ');sb.append(a[i]);} this.writeLine(sb.toString()); } } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class Tri { public Tri(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; public class C{ static String s; static long val[]; static int N,size; static int index(char c){ if(c <= 'Z'){ return c - 'A'; }else{ return c - 'a' + ('Z' - 'A' + 1); } } static int l(int i){ return (i<<1)+1; } static int r(int i){ return (i<<1)+2; } static void setup(int l, int r, int i){ if(l==r){ val[i] = (1L<<index(s.charAt(l))); }else{ int mid = (l+r)/2; setup(l,mid,l(i)); setup(mid+1,r,r(i)); val[i] = val[l(i)] | val[r(i)]; } } static long query(int min, int max, int l, int r, int i){ if(min <= l && r <= max){ return val[i]; } if(max < l || r < min) return 0; int mid = (l+r)/2; return query(min,max,l,mid,l(i)) | query(min,max,mid+1,r,r(i)); } static long query(int min, int max){ return query(min,max,0,N-1,0); } static int binarySearch(int start, long toFind){ int max = N-1; int min = start; if(query(start,max) != toFind) return 1<<29; if(query(start,start) == toFind){ return 1; } int ret = max - min + 1; while(min + 1 < max){ int mid = (min+max)/2; if(query(start,mid) == toFind){ max = mid; }else{ min = mid; } } return max-start+1; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); N = sc.nextInt(); s = sc.next(); int size = 1; while(size <= N) size*=2; val = new long[size*2]; setup(0,N-1,0); long toFind = query(0,N-1,0,N-1,0); long ans = 1L<<29; for(int i = 0; i < N; i++) ans = Math.min(ans,binarySearch(i,toFind)); System.out.println(ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; public class C { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintStream out = System.out; public static void main(String[] args) throws NumberFormatException, IOException { int n = Integer.parseInt(in.readLine()); char[] s = in.readLine().toCharArray(); HashSet<Character> all = new HashSet<Character>(); for (char c : s) all.add(c); int totalCount = all.size(); HashMap<Character, Integer> cnts = new HashMap<Character, Integer>(); int ans = Integer.MAX_VALUE; int x = 0; for (int y = 0; y < n; ++y) { if (!cnts.containsKey(s[y])) cnts.put(s[y], 0); cnts.put(s[y], cnts.get(s[y]) + 1); if (cnts.size() < totalCount) continue; while (cnts.get(s[x]) > 1) { cnts.put(s[x], cnts.get(s[x]) - 1); ++x; } ans = Math.min(ans, y - x + 1); } out.println(ans); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created by Daniil on 5/29/2016. */ public class TaskB { public static int strIndex; public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); char[] s = scanner.next().toCharArray(); int[][] r = new int[n][54]; Set<Character> chars = new HashSet<>(); for (int i= 0 ;i < n; ++ i)chars.add(s[i]); List<Character> all = new ArrayList<>(); for (Character c: chars)all.add(c); for (int i = n - 1; i >= 0; -- i){ for (int j = 0;j < 54; ++ j){ if (i == n - 1){ r[i][j] = -1; }else { r[i][j] = r[i + 1][j]; } } r[i][getCode(s[i])] = i; } int res = n; for (int i =0; i < n; ++ i){ int mx = 1; boolean fl = false; for (Character c: all){ if (r[i][getCode(c)] == -1){ fl = true; break; } mx = Math.max(mx, r[i][getCode(c)] - i + 1); } if (fl){ System.out.println(res); return; } res = Math.min(res, mx); } System.out.println(res); scanner.close(); //reader.close(); } public static int getCode(char a){ if (Character.isUpperCase(a))return a - 'A'; return (a - 'a') + 26; } public static int getLetter(int n){ if (n > 25)return (char)((n - 26) + 'a'); return (char)((n) + 'A'); } static class IO{ BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void init() { try { reader = new BufferedReader(new InputStreamReader(System.in),8*1024); writer = new PrintWriter(System.out); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void destroy() { writer.close(); System.exit(0); } void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } void println(Object... objects) { print(objects); writer.println(); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P701A { Map<Character, Integer> cc = new HashMap(72); void add(char c) { cc.put(c, cc.getOrDefault(c, 0) + 1); } void rem(char c) { Integer cnt = cc.get(c) - 1; if (cnt != 0) { cc.put(c, cnt); } else { cc.remove(c); } } public void run() throws Exception { int n = nextInt(); char [] s = next().toCharArray(); BitSet bs = new BitSet(); for (char c : s) { bs.set(c); } int t = bs.cardinality(); int m = Integer.MAX_VALUE; for (int i = 0, j = 0; i < n; i++) { while ((j < n) && (cc.size() < t)) { add(s[j]); j++; } if (cc.size() == t) { m = Math.min(m, j - i); } rem(s[i]); } println(m); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P701A().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { return ((b > 0) ? gcd(b, a % b) : a); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String in1 = in.readLine(); String store = ""; HashSet<Character> contain = new HashSet<Character>(); for(int i = 0; i < n;i++){ if(!contain.contains(in1.charAt(i))){ store += in1.charAt(i); contain.add(in1.charAt(i)); } } int[] index = new int[store.length()]; for(int i = 0; i < store.length(); i++){ index [i] = -1; } HashSet<Integer> index2 = new HashSet<Integer>(); ArrayList<Integer> index3 = new ArrayList<Integer>(); int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++){ int index4 = store.indexOf(in1.charAt(i)); if(index[index4] == -1){ index[index4] = i; index2.add(i); index3.add(i); } else{ index2.remove(index[index4]); index2.add(i); index3.add(i); index[index4] = i; } if(index2.size() == index.length){ while(!index2.contains(index3.get(0))){ index3.remove(0); } min = Math.min(min, i - index3.get(0)+ 1); } } System.out.println(min); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.* ; import java.util.* ; public class Codeshefcode { final static long r = 1000000007 ; static FasterScanner ip = new FasterScanner() ; static PrintWriter op = new PrintWriter(System.out) ; public static void main(String[] args) throws IOException{ int n = ip.i() ; TreeMap<Character,Integer> map = new TreeMap<Character,Integer>() ; TreeSet<Character> set = new TreeSet<Character>() ; char c[] = ip.S().toCharArray() ; for(char t : c) set.add(t) ; int size = set.size() ; for(int i=0 ; i<size ; i++) map.put(set.pollFirst(),i) ; int a[] = new int[n] ; for(int i=0 ; i<n ; i++) a[i]=map.get(c[i]) ; int erl[][] = new int[size][n] ; for(int i=0 ; i<size ; i++) for(int j=n-1 ; j>=0 ; j--) erl[i][j]=(a[j]==i) ? j : (j==n-1 ? -1 : erl[i][j+1]) ; long min = Long.MAX_VALUE ; for(int i=0 ; i<n ; i++){ long maxt = Long.MIN_VALUE ; for(int j=0 ; j<size ; j++) if(erl[j][i]!=-1) maxt = Long.max(maxt,(erl[j][i]-i+1)) ; else{ maxt = Long.MAX_VALUE ; break ; } min = Long.min(min,maxt) ; } op.print(min) ; Finish() ; } static void Finish(){ op.flush(); op.close(); } } @SuppressWarnings("serial") class MyList extends ArrayList<Long>{ } class pair { private int x ; private int y ; pair(int a,int b){ x=a ; y=b ; } public int x(){ return x ; } public int y(){ return y ; } } class FasterScanner { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FasterScanner() { this(System.in); } public FasterScanner(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String S(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); }while (!isSpaceChar(c)); return res.toString(); } public long l(){ int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); }while(!isSpaceChar(c)); return res * sgn; } public int i(){ int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); }while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.Random; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); char[] str = IOUtils.readCharArray(in, n); for (int i = 0; i < n; i++) { if (str[i] <= 'Z') { str[i] = (char) (str[i] - 'A'); } else { str[i] = (char) (str[i] - 'a' + 26); } } IntHashSet set = new IntHashSet(); for (char c : str) { set.add(c); } int max = 26 + 26; int[][] next = new int[max][n]; ArrayUtils.fill(next, -1); for (int i = n - 2; i >= 0; i--) { for (int ch = 0; ch < max; ch++) { next[ch][i] = next[ch][i + 1]; } next[str[i + 1]][i] = i + 1; } int ans = (int) 1e9; final int tagetCnt = set.size(); for (int s = 0; s < n; s++) { boolean[] used = new boolean[max]; used[str[s]] = true; int cnt = 1; int pos = s; while (cnt < tagetCnt) { int nextPos = n; for (int ch = 0; ch < max; ch++) { if (!used[ch]) { if (next[ch][pos] == -1) { continue; } nextPos = Math.min(nextPos, next[ch][pos]); } } pos = nextPos; if (nextPos == n) { break; } ++cnt; used[str[nextPos]] = true; } if (pos == n) { break; } ans = Math.min(ans, pos - s + 1); } out.printLine(ans); } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static class IntHashSet extends IntAbstractStream implements IntSet { private static final Random RND = new Random(); private static final int[] SHIFTS = new int[4]; private static final byte PRESENT_MASK = 1; private static final byte REMOVED_MASK = 2; private int size; private int realSize; private int[] values; private byte[] present; private int step; private int ratio; static { for (int i = 0; i < 4; i++) { SHIFTS[i] = RND.nextInt(31) + 1; } } public IntHashSet() { this(3); } public IntHashSet(int capacity) { capacity = Math.max(capacity, 3); values = new int[capacity]; present = new byte[capacity]; ratio = 2; initStep(capacity); } public IntHashSet(IntCollection c) { this(c.size()); addAll(c); } public IntHashSet(int[] arr) { this(new IntArray(arr)); } private void initStep(int capacity) { step = RND.nextInt(capacity - 2) + 1; while (IntegerUtils.gcd(step, capacity) != 1) { step++; } } public IntIterator intIterator() { return new IntIterator() { private int position = size == 0 ? values.length : -1; public int value() throws NoSuchElementException { if (position == -1) { advance(); } if (position >= values.length) { throw new NoSuchElementException(); } if ((present[position] & PRESENT_MASK) == 0) { throw new IllegalStateException(); } return values[position]; } public boolean advance() throws NoSuchElementException { if (position >= values.length) { throw new NoSuchElementException(); } position++; while (position < values.length && (present[position] & PRESENT_MASK) == 0) { position++; } return isValid(); } public boolean isValid() { return position < values.length; } public void remove() { if ((present[position] & PRESENT_MASK) == 0) { throw new IllegalStateException(); } present[position] = REMOVED_MASK; } }; } public int size() { return size; } public void add(int value) { ensureCapacity((realSize + 1) * ratio + 2); int current = getHash(value); while (present[current] != 0) { if ((present[current] & PRESENT_MASK) != 0 && values[current] == value) { return; } current += step; if (current >= values.length) { current -= values.length; } } while ((present[current] & PRESENT_MASK) != 0) { current += step; if (current >= values.length) { current -= values.length; } } if (present[current] == 0) { realSize++; } present[current] = PRESENT_MASK; values[current] = value; size++; } private int getHash(int value) { int hash = IntHash.hash(value); int result = hash; for (int i : SHIFTS) { result ^= hash >> i; } result %= values.length; if (result < 0) { result += values.length; } return result; } private void ensureCapacity(int capacity) { if (values.length < capacity) { capacity = Math.max(capacity * 2, values.length); rebuild(capacity); } } private void rebuild(int capacity) { initStep(capacity); int[] oldValues = values; byte[] oldPresent = present; values = new int[capacity]; present = new byte[capacity]; size = 0; realSize = 0; for (int i = 0; i < oldValues.length; i++) { if ((oldPresent[i] & PRESENT_MASK) == PRESENT_MASK) { add(oldValues[i]); } } } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } } static class IntegerUtils { public static int gcd(int a, int b) { a = Math.abs(a); b = Math.abs(b); while (b != 0) { int temp = a % b; a = b; b = temp; } return a; } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntHash { private IntHash() { } public static int hash(int c) { return c; } } static interface IntReversableCollection extends IntCollection { } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface IntSet extends IntCollection { } static class IOUtils { public static char[] readCharArray(InputReader in, int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = in.readCharacter(); } return array; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) { Arrays.fill(row, value); } } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public int[] parse(FastScanner in, int n) { String s = in.next(); int[] temp = new int[n]; for (int i = 0; i < n; ++i) { temp[i] = s.charAt(i) - 'A'; } return temp; } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] s = parse(in, n); Map<Integer, TreeSet<Integer>> map = new HashMap<>(); for (int i = 0; i < n; ++i) { if (map.containsKey(s[i])) { map.get(s[i]).add(i); } else { TreeSet<Integer> temp = new TreeSet<>(); temp.add(i); map.put(s[i], temp); } } int ans = Integer.MAX_VALUE; for (int i = 0; i < n; ++i) { int finalI = i; final Int integer = new Int(); integer.x = i; map.forEach((Integer x, TreeSet set) -> { if (x != s[finalI]) { Integer temp = (Integer) set.higher(finalI); if (temp == null) { integer.x = -2; } else { if (integer.x != -2) integer.x = Integer.max(integer.x, temp); } } else { } }); if (integer.x != -2) { ans = Integer.min(ans, integer.x - i + 1); } } out.print(ans); } public class Int { int x; public Int() { x = -1; } } } static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ while (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } private long nextLong() throws Exception{ return Long.parseLong(next()); } private double nextDouble() throws Exception{ return Double.parseDouble(next()); } final int oo = Integer.MAX_VALUE; int [][]s; int n, ALL; public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); n = nextInt(); char []a = next().toCharArray(); s = new int[n][52]; boolean []set = new boolean[52]; for(int i = 0; i < n; ++i) { int pos = get(a[i]); if (!set[pos]) { ++ALL; set[pos] = true; } for(int j = 0; j < 52; ++j) { if (i > 0) { s[i][j] += s[i-1][j]; } if (j == pos) { s[i][j]++; } } } int ret = oo; for(int i = 0; i < n; ++i) { ret = Math.min(ret, get(i)); } out.println(ret); out.close(); } private int get(int i) { int lo = i - 1, hi = n; while(hi - lo > 1) { int m = lo + (hi - lo) / 2; int c = 0; for(int j = 0; j < 52; ++j) { if (sum(j, i, m) > 0) { ++c; } } if (c < ALL) { lo = m; } else { hi = m; } } if (hi != n) { return hi - i + 1; } return oo; } private int sum(int pos, int l, int r) { int ret = s[r][pos]; if (l > 0) ret -= s[l - 1][pos]; return ret; } private int get(char x) { if ('a' <= x && x <= 'z') return (int)(x - 'a'); return (int)(x - 'A' + 26); } public static void main(String[] args) throws Exception{ new Main().run(); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); String word = in.next(); int cnt[] = new int[1000]; int let = 0; Set<Character> set = new TreeSet<>(); for (int i = 0; i < word.length(); i++) { set.add(word.charAt(i)); } int uniq = set.size(); int i = 0, j = -1; int ans = Integer.MAX_VALUE; while (i < N && j < N) { while (j + 1 < N && let < uniq) { j++; if (cnt[word.charAt(j)] == 0) { let++; } cnt[word.charAt(j)]++; } if (let == uniq) ans = Math.min(ans, j - i + 1); cnt[word.charAt(i)]--; if (cnt[word.charAt(i)] == 0) let--; i++; } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); char[] ps = in.readLine().toCharArray(); HashMap<Character, TreeSet<Integer>> locs = new HashMap<Character, TreeSet<Integer>>(); HashSet<Character> poks = new HashSet<Character>(); int lastNew = n; for (int i = 0; i < n; i++) { if (!poks.contains(ps[i])) { poks.add(ps[i]); locs.put(ps[i], new TreeSet<Integer>()); lastNew = i; } locs.get(ps[i]).add(i); } int max = lastNew; int minRange = max+1; for (int min = 0; min < n; min++) { char pAtMin = ps[min]; Integer nextInd = locs.get(pAtMin).higher(min); if (nextInd == null) break; max = Math.max(max, nextInd); minRange = Math.min(minRange, max-min); } System.out.println(minRange); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Random; public class ProblemC { public static void main(String[] args) throws IOException { init(); new ProblemC().run(); out.flush(); out.close(); } static void init() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); in.ordinaryChars(0, 65535); in.wordChars(0, 65535); in.whitespaceChars(' ', ' '); in.whitespaceChars('\n', '\n'); in.whitespaceChars('\r', '\r'); } // класс для пар class Pair<L, R> { private final L X; private final R Y; public Pair(L X, R Y) { this.X = X; this.Y = Y; } public L getX() { return X; } public R getY() { return Y; } @Override public int hashCode() { return X.hashCode() ^ Y.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair pairo = (Pair) o; return X.equals(pairo.getX()) && Y.equals(pairo.getY()); } } static final long INFL = 200000000000000000L; static final int INF = 2000000000; static final boolean DEBUG = true; static StreamTokenizer in; static PrintWriter out; static void print(String s) { print(s, 0); } static void print(String s, int debug) { if (debug == 0 || DEBUG) { out.print(s); } } static void println(String s) { println(s, 0); } static void println(String s, int debug) { if (debug == 0 || DEBUG) { out.println(s); } } static void printArray(int[] arr) { println(Arrays.toString(arr)); } static void printArray(char[] arr) { println(Arrays.toString(arr)); } static void printArray(String[] arr) { println(Arrays.toString(arr)); } static void sort(int[] a) { Random rnd = new Random(); for (int i = a.length - 1; i > 0; i--) { int index = rnd.nextInt(i); a[i] ^= a[index]; a[index] ^= a[i]; a[i] ^= a[index]; } Arrays.sort(a); } static char[] inChars; static int inCharsInd; static String next() throws IOException { in.nextToken(); return in.sval; } static char nextChar() throws IOException { while (inChars == null || inCharsInd >= inChars.length) { inChars = next().toCharArray(); inCharsInd = 0; } return inChars[inCharsInd++]; } static int nextInt() throws IOException { return Integer.valueOf(next()); } static double nextDouble() throws IOException { return Double.valueOf(next()); } static long nextLong() throws IOException { return Long.valueOf(next()); } private void run() throws IOException { solve(); } int K, L, M, N, P; private void solve() throws IOException { int[] countChars = new int['z' + 1]; boolean[] gotIt = new boolean['z' + 1]; int N = nextInt(); int fullCount = 0; char[] chars = next().toCharArray(); for (int i = 0; i < N; i++) { if (countChars[chars[i]] == 0) fullCount++; countChars[chars[i]]++; } // out.println(fullCount); countChars = new int['z' + 1]; int answer = N; int start = 0, finish = 0; countChars[chars[start]]++; fullCount--; while (finish+1 < N){ finish++; if (countChars[chars[finish]] == 0) { fullCount--; } countChars[chars[finish]]++; while (countChars[chars[start]] > 1){ countChars[chars[start]]--; start++; } while (fullCount == 0){ // out.println("start = " + (start+1)); // out.println("finish = " + (finish+1)); answer = Math.min(answer, finish-start+1); countChars[chars[start]]--; if (countChars[chars[start]] == 0) fullCount++; start++; } } out.println(answer); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author xwchen */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); int[] cnt = new int[26]; int[] cnt2 = new int[26]; int j = 0; int res = n; HashSet<Character> set = new HashSet<Character>(); for (char c : s.toCharArray()) { set.add(c); } int m = set.size(); for (int i = 0; i < n; ++i) { if (Character.isLowerCase(s.charAt(i))) { cnt[s.charAt(i) - 'a']++; } else { cnt2[s.charAt(i) - 'A']++; } while (isOK(cnt, cnt2, m)) { res = Math.min(res, i - j + 1); if (Character.isLowerCase(s.charAt(j))) { cnt[s.charAt(j) - 'a']--; } else { cnt2[s.charAt(j) - 'A']--; } ++j; } } out.println(res); } boolean isOK(int[] cnt, int[] cnt2, int m) { int c = 0; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { ++c; } } for (int i = 0; i < 26; ++i) { if (cnt2[i] > 0) { ++c; } } return c >= m; } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.InputMismatchException; public class Cf2207C { private static InputReader in = new InputReader(System.in); private static OutputWriter out = new OutputWriter(System.out); private static void solve() throws Exception { int n = in.readInt(); String s = in.readString(); int[] count = new int[200]; boolean[] flag = new boolean[200]; for(int i=0; i<n; ++i){ flag[s.charAt(i)] = true; } int ref = 0; for(int i=0; i<200; ++i){ if(flag[i]){ ref++; } } int total = 0; int min = Integer.MAX_VALUE; int j = 0; for(int i=0; i<n; ++i){ if((j==n)&&(total<ref)){ break; } if(total==ref){ min = Math.min(min,j-i); count[s.charAt(i)]--; if(count[s.charAt(i)]==0){ total--; } continue; } for(;j<n; ++j){ count[s.charAt(j)]++; if(count[s.charAt(j)]==1){ total++; } if(total==ref){ min = Math.min(min,j-i+1); j++; break; } } count[s.charAt(i)]--; if(count[s.charAt(i)]==0){ total--; } } out.println(min); } public static void main(String[] args) throws Exception { solve(); out.close(); } private static class InputReader { private InputStream stream; private byte[] buffer; private int currentIndex; private int bytesRead; public InputReader(InputStream stream) { this.stream = stream; buffer = new byte[16384]; } public InputReader(InputStream stream, int bufferSize) { this.stream = stream; buffer = new byte[bufferSize]; } private int read() throws IOException { if (currentIndex >= bytesRead) { currentIndex = 0; bytesRead = stream.read(buffer); if (bytesRead <= 0) { return -1; } } return buffer[currentIndex++]; } public String readString() throws IOException { int c = read(); while (!isPrintable(c)) { c = read(); } StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (isPrintable(c)); return result.toString(); } public int readInt() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } int result = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } result *= 10; result += (c - '0'); c = read(); } while (isPrintable(c)); return sign * result; } public long readLong() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } long result = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } result *= 10; result += (c - '0'); c = read(); } while (isPrintable(c)); return sign * result; } public double readDouble() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } boolean fraction = false; double multiplier = 1; double result = 0; do { if ((c == 'e') || (c == 'E')) { return sign * result * Math.pow(10, readInt()); } if ((c < '0') || (c > '9')) { if ((c == '.') && (!fraction)) { fraction = true; c = read(); continue; } throw new InputMismatchException(); } if (fraction) { multiplier /= 10; result += (c - '0') * multiplier; c = read(); } else { result *= 10; result += (c - '0'); c = read(); } } while (isPrintable(c)); return sign * result; } private boolean isPrintable(int c) { return ((c > 32) && (c < 127)); } } private static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStream; import java.util.HashSet; public class C { public static void main(String args[]) { Kattio sc = new Kattio(System.in); int n = sc.getInt(); String s = sc.getWord(); int[] found = new int['z' + 1]; int amount = 0; for(int i = 0; i<s.length(); i++) { char c = s.charAt(i); if(found[c] == 0) amount++; found[c]++; } int contains[] = new int['z' + 1]; int min = n; int start = 0; int end = 0; int in = 0; while(true) { if(in<amount) { if(end == n) break; char c = s.charAt(end); if(contains[c] == 0) in++; contains[c]++; end++; } else { if(min>end-start) min = end-start; char c = s.charAt(start); if(contains[c] == 1) in--; contains[c]--; start++; } } System.out.println(min); } } class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * @author grozhd */ public class P3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = ""; while (s.length() == 0) { s = sc.nextLine(); } char[] pokemons = s.toCharArray(); Set<Character> pokemonTypes = new HashSet<>(); for (int i = 0; i < n; i++) { pokemonTypes.add(pokemons[i]); } int types = pokemonTypes.size(); int l = 0; int r = 0; int min = n; Map<Character, Integer> currentPokemons = new HashMap<>(); while (r < n) { while (currentPokemons.size() < types && r < n) { char pokemon = pokemons[r++]; currentPokemons.merge(pokemon, 1, (a, b) -> a + b); } min = Math.min(r - l, min); while (currentPokemons.size() == types) { char pokemon = pokemons[l++]; if (currentPokemons.get(pokemon) == 1) { currentPokemons.remove(pokemon); } else { min = Math.min(r - l, min); currentPokemons.put(pokemon, currentPokemons.get(pokemon) - 1); } } } min = Math.min(min, r - l + 1); min = Math.max(min, types); System.out.println(min); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class Main { void change(int [] all, char c, int val) { if (Character.isUpperCase(c)) all[c - 'A' + 26] += val; else all[c - 'a'] += val; } int countDistinct(int [] a) { int res = 0; for (int i = 0 ; i< a.length ; i++) { if (a[i] > 0) res ++; } return res; } public void solve() throws IOException { int n = nextInt(); String s = next(); int [] all = new int[52]; for (int i = 0 ; i < s.length() ; i++) { char c = s.charAt(i); change(all, c, 1); } int distinct = countDistinct(all); int [] window = new int[52]; int best = n; for (int i = 0, j = 0 ; i < s.length() ; i++) { if (i > 0) { change(window, s.charAt(i-1), -1); } while (j < s.length()) { if (countDistinct(window) == distinct) break; change(window, s.charAt(j), 1); j ++; } if (countDistinct(window) < distinct) break; best = Math.min(best, j - i); } out.println(best); } BufferedReader bf; StringTokenizer st; PrintWriter out; public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public Main() throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); bf.close(); out.close(); } public static void main(String args[]) throws IOException { new Main(); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; public class Main { private static Scanner in = new Scanner(System.in); public static void main(String args[]){ int n = in.nextInt(); String s = in.next(); if(n==1) System.out.println("1"); else{ int j=0,i=1,ans=s.length(); int h[]=new int[128]; h[(int)s.charAt(0)]=1; while(i<n){ if(h[(int)s.charAt(i)]==0) ans = i-j+1; h[(int) s.charAt(i)]++; while(j<i && h[(int)s.charAt(j)]>1){ h[(int)s.charAt(j)]--; j++; ans = Math.min(ans, i-j+1); } i++; } System.out.println(ans); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class CTask { public static void main(String[] args) throws IOException { MyInputReader in = new MyInputReader(System.in); HashMap<Character, Integer> m = new HashMap<Character, Integer>(); int n = in.nextInt(); char[] s = in.next().toCharArray(); for (int i = 0; i < n; i++) { m.put(s[i], 0); } int mx = m.size(); int start = 0; int end = 0; int min = Integer.MAX_VALUE; int cur = 0; while (end < n) { while (end < n && cur != mx) { int x = m.get(s[end]); if (x == 0) { cur += 1; } m.put(s[end], x + 1); end += 1; } while (start <= end && cur == mx) { int x = m.get(s[start]); m.put(s[start], x - 1); if (x - 1 == 0) { cur -= 1; } start += 1; } min = Math.min(min, end - start + 1); } System.out.println(min); } static class Pair { long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; return y == pair.y; } @Override public int hashCode() { int result = (int) (x ^ (x >>> 32)); result = 31 * result + (int) (y ^ (y >>> 32)); return result; } } static class MyInputReader { public BufferedReader reader; public StringTokenizer tokenizer; public MyInputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rene */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); HashMap<Character, Integer> indexMap = new HashMap<>(); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (!indexMap.containsKey(c)) { indexMap.put(c, indexMap.size()); } } int[] last = new int[indexMap.size()]; Arrays.fill(last, -1_000_000); int answer = n; for (int i = 0; i < n; i++) { int index = indexMap.get(s.charAt(i)); last[index] = i; int first = i; for (int a : last) first = Math.min(first, a); int visits = i - first + 1; answer = Math.min(answer, visits); } out.println(answer); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Hashtable; import java.util.Scanner; import java.util.TreeSet; public class Main3 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = sc.nextInt(); String S = sc.next(); HashSet<Character> unique = new HashSet<>(); for(char c : S.toCharArray()){ unique.add(c); } int number = unique.size(); Hashtable<Character, Integer> indexes = new Hashtable<>(); TreeSet<Integer> tree = new TreeSet<>(); int min = N+1; int total = 0; for(int i = 0; i<N; i++){ char c = S.charAt(i); if(!indexes.containsKey(c)){ total++; indexes.put(c, i); tree.add(i); } else{ int old = indexes.get(c); indexes.put(c, i); tree.remove(old); tree.add(i); } if(total == number){ int dist = tree.last() - tree.first() + 1; min = Math.min(dist, min); } } System.out.println(min); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class CF1009E { static final int MD = 998244353; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] aa = new int[1 + n]; for (int i = 1, a = 0; i <= n; i++) aa[i] = a = (a + Integer.parseInt(st.nextToken())) % MD; int[] pp = new int[n]; pp[0] = 1; for (int i = 1, p = 1; i < n; i++) { pp[i] = p; p = p * 2 % MD; } int d = 0; long ans = 0; for (int i = n - 1; i >= 0; i--) { // rest at i d = (d * 2 % MD + aa[n - 1 - i]) % MD; // rest again before n ans = (ans + (long) (d + aa[n - i]) * pp[i]) % MD; } System.out.println(ans); } }
linear
1009_E. Intercity Travelling
CODEFORCES