src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.io.InputStreamReader; import java.util.Scanner; public class Hexadecimal { public static void main(String [] args){ Scanner s = new Scanner(new InputStreamReader(System.in)); int x = s.nextInt(); System.out.println(x + " " + 0 + " " + 0); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { new A().solve(); } void solve() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); if (n == 0) { System.out.println("0 0 0"); return; } int p2 = 0; int p1 = 1; while (true) { int now = p2 + p1; if (n == now) { System.out.println("0 " + p1 + " " + p2); return; } else { p2 = p1; p1 = now; } } } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class HexTheorem { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int x = Integer.parseInt(read.readLine()); System.out.println("0 0 "+x); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.text.*; import java.math.*; import java.util.*; public class Hexadec implements Runnable { final static String taskname = "filename"; public void solve() throws Exception { // int n = iread(); int n = Integer.parseInt(in.readLine()); out.write(n + " "+0+" "+0); // out.write(ans_path + "\n"); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(taskname + ".in")); // out = new BufferedWriter(new FileWriter(taskname + ".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { // Locale.setDefault(Locale.US); new Thread(new Hexadec()).start(); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner input = new Scanner(System.in); long num =0; num = input.nextLong(); while (num<0 || num>Math.pow(10,9)) { System.out.println("Invalid"); num = input.nextLong(); } System.out.println("0 0 "+num); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; 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); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } } class TaskA { int n; int m; String answer = "I'm too stupid to solve this problem"; public void solve(InputReader in, PrintWriter out) { n = in.nextInt(); out.println("0 0 " + n); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.Scanner; public class N1_CF_199A { public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); if( n == 0) { System.out.println(0); System.out.println(0); System.out.println(0); return; } int i = 0 , j = 1; while(true) { int t = i + j; if( t == n) break; i = j; j = t; } System.out.println(i); System.out.println(j); System.out.println(0); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class a extends Thread { BufferedReader bf; PrintWriter out; FastScanner in; void solve() throws Exception { long n = in.nextLong(); long f[] = new long[2001]; int i = 2; f[0] = 0; f[1] = 1; while (true){ f[i] = f[i-1] + f[i-2]; if (f[i] < n) i++; else break; } if (n == 1) out.println("1 0 0"); else if (n == 0) out.println("0 0 0"); else if (i - 3 >= 0) out.println(f[i-2] +" " + f[i-2] + " " +f[i-3]); else out.println("I'm too stupid to solve this problem"); } public void run() { try { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); in = new FastScanner(bf); solve(); out.flush(); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } } public static void main(String args[]) { new a().start(); } class FastScanner { BufferedReader bf; StringTokenizer st; public FastScanner(BufferedReader bf) { this.bf = bf; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.readLine()); } return st.nextToken(); } 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()); } public BigInteger nextBigInteger() throws Exception { return new BigInteger(nextToken()); } } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); List<Long> fi = new ArrayList<Long>(); fi.add((long) 0); fi.add((long) 1); while (fi.get(fi.size()-1)<n) { fi.add(fi.get(fi.size()-1)+fi.get(fi.size()-2)); } int last = fi.size()-1; long z = last-1>=0 ? fi.get(last-1) : 0; long y = last-3>=0 ? fi.get(last-3) : 0; long x = last-4>=0 ? fi.get(last-4) : 0; if (x+y+z<n) x=1; System.out.println(x+" "+y+" "+z); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import java.io.*; import java.math.*; import java.util.*; @SuppressWarnings("unused") public class A { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); long n = in.nextLong(); System.out.println("0 0 " + n); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.IOException; import java.util.Scanner; public class A199 { static int n[][] = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; public static void main(String[] args) throws IOException { new A199().solve(); } public void solve() throws IOException { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); // int f1 = 0; // int f2 = 1; // // while(true){ // int t = f1 + f2; // if(t == N){ // //guaranteed that n is a Fibonacci number // break; // } // f1 = f2; // f2 = t; // } System.out.println("0 0 " + N ); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: vaibhav mittal * Date: 23/6/12 * Time: 1:15 AM * To change this template use File | Settings | File Templates. */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); long n = in.nextLong(); out.println(0 + " " + 0 + " " + n); in.close(); out.close(); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; import java.math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import java.lang.Math.*; public class two_squares { public static void main(String[] args) throws Exception { new two_squares().run(); } public void run() throws Exception { FastIO file = new FastIO(); double x1 = file.nextInt(); double y1 = file.nextInt(); double x2 = file.nextInt(); double y2 = file.nextInt(); double x3 = file.nextInt(); double y3 = file.nextInt(); double x4 = file.nextInt(); double y4 = file.nextInt(); double minx1, maxx1, miny1, maxy1; minx1 = Math.min(x1, Math.min(x2, Math.min(x3, x4))); maxx1 = Math.max(x1, Math.max(x2, Math.max(x3, x4))); miny1 = Math.min(y1, Math.min(y2, Math.min(y3, y4))); maxy1 = Math.max(y1, Math.max(y2, Math.max(y3, y4))); double x5 = file.nextInt(); double y5 = file.nextInt(); double x6 = file.nextInt(); double y6 = file.nextInt(); double x7 = file.nextInt(); double y7 = file.nextInt(); double x8 = file.nextInt(); double y8 = file.nextInt(); double minx2, maxx2, miny2, maxy2; minx2 = Math.min(x5, Math.min(x6, Math.min(x7, x8))); maxx2 = Math.max(x5, Math.max(x6, Math.max(x7, x8))); miny2 = Math.min(y5, Math.min(y6, Math.min(y7, y8))); maxy2 = Math.max(y5, Math.max(y6, Math.max(y7, y8))); Point _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16; _1 = new Point(x1, y1); _2 = new Point(x2, y2); _3 = new Point(x3, y3); _4 = new Point(x4, y4); _5 = new Point(x5, y5); _6 = new Point(x6, y6); _7 = new Point(x7, y7); _8 = new Point(x8, y8); _9 = new Point(minx1, maxy1); _10 = new Point(minx1, miny1); _11 = new Point(maxx1, maxy1); _12 = new Point(maxx1, miny1); double m1 = (minx2 + maxx2) / 2; double m2 = (miny2 + maxy2) / 2; _13 = new Point(minx2, m2); _14 = new Point(m1, miny2); _15 = new Point(maxx2, m2); _16 = new Point(m1, maxy2); Point[] a = {_1, _2, _3, _4}; Point[] b = {_5, _6, _7, _8}; boolean works = false; Line[] aa = {new Line(_9,_10), new Line(_10, _12), new Line(_12, _11), new Line(_11, _9)}; Line[] bb = {new Line(_13, _14), new Line(_14, _15), new Line(_15, _16), new Line(_16, _13)}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (aa[i].intersection(bb[i]) != null) { works = true; } } } for (Point p : b) { if (p.x >= minx1 && p.x <= maxx1 && p.y >= miny1 && p.y <= maxy1) { works = true; } } for (Point p : a) { boolean result = false; for (int i = 0, j = b.length - 1; i < b.length; j = i++) { if ((b[i].y > p.y) != (b[j].y > p.y) && (p.x < (b[j].x - b[i].x) * (p.y - b[i].y) / (b[j].y-b[i].y) + b[i].x)) { result = !result; } } if (result) works = true; } System.out.println(works ? "YES" : "NO"); } public static class Point { double x, y; public Point(double a, double b) { x = a; y = b; } } public static class Line { Point a, b; public Line(Point x, Point y) { a = x; b = y; } public Point intersection(Line o) { double x1 = a.x; double y1 = a.y; double x2 = b.x; double y2 = b.y; double x3 = o.a.x; double y3 = o.a.y; double x4 = o.b.x; double y4 = o.b.y; double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))/denom; double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))/denom; if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) { return new Point((int) (x1 + ua*(x2 - x1)), (int) (y1 + ua*(y2 - y1))); } return null; } } public static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() { 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; } } public static long pow(long n, long p, long mod) { if (p == 0) return 1; if (p == 1) return n % mod; if (p % 2 == 0) { long temp = pow(n, p / 2, mod); return (temp * temp) % mod; } else { long temp = pow(n, p / 2, mod); temp = (temp * temp) % mod; return (temp * n) % mod; } } public static long pow(long n, long p) { if (p == 0) return 1; if (p == 1) return n; if (p % 2 == 0) { long temp = pow(n, p / 2); return (temp * temp); } else { long temp = pow(n, p / 2); temp = (temp * temp); return (temp * n); } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } }
constant
994_C. Two Squares
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; public class C { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Point [] square = new Point [4] ; Point [] rotSquare = new Point[4] ; for(int i = 0 ; i < 4 ;i++) square[i] = new Point(sc.nextInt() , sc.nextInt()); for(int i = 0 ; i < 4 ;i++) rotSquare[i] = new Point(sc.nextInt() , sc.nextInt()); boolean can = false ; for(int x = -100 ; x <= 100 ; x++) for(int y = -100 ; y <= 100 ; y++) can |= inside(new Point(x , y), square) & inside(new Point (x , y), rotSquare); out.println(can ? "YES" : "NO"); out.flush(); out.close(); } static int crossProduct(Point a , Point b) { int ans = a.x * b.y - a.y * b.x ; if(ans < 0)return -1 ; if(ans == 0) return 0 ; return 1 ; } static boolean inside(Point a , Point [] points) { boolean allPos = true ; boolean allNeg = true ; for(int i = 0 ; i < 4 ; i++) { Point v1 = new Point (points[i].x - a.x , points[i].y - a.y) ; Point v2 = new Point (points[(i + 1) % 4].x - a.x , points[(i + 1) % 4].y - a.y) ; allPos &= crossProduct(v1, v2) >= 0; allNeg &= crossProduct(v1, v2) <= 0; } return allPos | allNeg ; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
constant
994_C. Two Squares
CODEFORCES
import java.util.*; import java.io.*; public class C994{ static double area(double x1,double y1,double x2,double y2,double x3,double y3){ return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } public static void main(String args[])throws IOException{ Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw=new PrintWriter(System.out); int x11=sc.nextInt(); int y11=sc.nextInt(); int x12=sc.nextInt(); int y12=sc.nextInt(); int x13=sc.nextInt(); int y13=sc.nextInt(); int x14=sc.nextInt(); int y14=sc.nextInt(); double x1c=(x11+x12+x13+x14)/4.0; double y1c=(y11+y12+y13+y14)/4.0; int x21=sc.nextInt(); int y21=sc.nextInt(); int x22=sc.nextInt(); int y22=sc.nextInt(); int x23=sc.nextInt(); int y23=sc.nextInt(); int x24=sc.nextInt(); int y24=sc.nextInt(); double x2c=(x21+x22+x23+x24)/4.0; double y2c=(y21+y22+y23+y24)/4.0; double a1=area(x11,y11,x12,y12,x13,y13)+area(x11,y11,x13,y13,x14,y14); double a2=area(x21,y21,x22,y22,x23,y23)+area(x21,y21,x23,y23,x24,y24); if(a1==area(x11,y11,x12,y12,x21,y21)+area(x11,y11,x21,y21,x14,y14)+area(x21,y21,x12,y12,x13,y13)+area(x21,y21,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x22,y22)+area(x11,y11,x22,y22,x14,y14)+area(x22,y22,x12,y12,x13,y13)+area(x22,y22,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x23,y23)+area(x11,y11,x23,y23,x14,y14)+area(x23,y23,x12,y12,x13,y13)+area(x23,y23,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x24,y24)+area(x11,y11,x24,y24,x14,y14)+area(x24,y24,x12,y12,x13,y13)+area(x24,y24,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x2c,y2c)+area(x11,y11,x2c,y2c,x14,y14)+area(x2c,y2c,x12,y12,x13,y13)+area(x2c,y2c,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x11,y11)+area(x21,y21,x11,y11,x24,y24)+area(x11,y11,x22,y22,x23,y23)+area(x11,y11,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x12,y12)+area(x21,y21,x12,y12,x24,y24)+area(x12,y12,x22,y22,x23,y23)+area(x12,y12,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x13,y13)+area(x21,y21,x13,y13,x24,y24)+area(x13,y13,x22,y22,x23,y23)+area(x13,y13,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x14,y14)+area(x21,y21,x14,y14,x24,y24)+area(x14,y14,x22,y22,x23,y23)+area(x14,y14,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x1c,y1c)+area(x21,y21,x14,y14,x2c,y2c)+area(x1c,y1c,x22,y22,x23,y23)+area(x1c,y1c,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } pw.println("NO"); pw.close(); } }
constant
994_C. Two Squares
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class TwoSquares { int INF = 1000; void solve() { int[][] s1 = new int[4][2]; for (int i = 0; i < 4; i++) { s1[i][0] = in.nextInt(); s1[i][1] = in.nextInt(); } int[][] s2 = new int[4][2]; for (int i = 0; i < 4; i++) { s2[i][0] = in.nextInt(); s2[i][1] = in.nextInt(); } if (ok(s1, s2)) { out.println("Yes"); return; } rotate(s1); rotate(s2); if (ok(s2, s1)) { out.println("Yes"); return; } out.println("No"); } void rotate(int[][] s) { for (int i = 0; i < 4; i++) { int x = s[i][0], y = s[i][1]; s[i][0] = x - y; s[i][1] = x + y; } } boolean ok(int[][] s1, int[][] s2) { int xmin = INF, xmax = -INF, ymin = INF, ymax = -INF; for (int i = 0; i < 4; i++) { xmin = Math.min(xmin, s1[i][0]); xmax = Math.max(xmax, s1[i][0]); ymin = Math.min(ymin, s1[i][1]); ymax = Math.max(ymax, s1[i][1]); } for (int i = 0; i < 4; i++) { if (s2[i][0] >= xmin && s2[i][0] <= xmax && s2[i][1] >= ymin && s2[i][1] <= ymax) return true; } int[] mid2 = new int[]{s2[0][0] + s2[2][0], s2[0][1] + s2[2][1]}; return mid2[0] >= xmin * 2 && mid2[0] <= xmax * 2 && mid2[1] >= ymin * 2 && mid2[1] <= ymax * 2; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new TwoSquares().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
constant
994_C. Two Squares
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class cf2 { static final double EPS = 1e-9; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //rec int xr1=sc.nextInt(), yr1=sc.nextInt(), xr2=sc.nextInt(),yr2=sc.nextInt(); int xr3=sc.nextInt(), yr3=sc.nextInt(), xr4=sc.nextInt(),yr4=sc.nextInt(); Point pr1 = new Point(xr1, yr1); Point pr2 = new Point(xr2, yr2); Point pr3 = new Point(xr3, yr3); Point pr4 = new Point(xr4, yr4); LineSegment lr1 = new LineSegment(pr1, pr2); LineSegment lr2 = new LineSegment(pr2, pr3); LineSegment lr3 = new LineSegment(pr3, pr4); LineSegment lr4 = new LineSegment(pr4, pr1); //diamond int xd1=sc.nextInt(), yd1=sc.nextInt(), xd2=sc.nextInt(),yd2=sc.nextInt(); int xd3=sc.nextInt(), yd3=sc.nextInt(), xd4=sc.nextInt(),yd4=sc.nextInt(); Point p1 = new Point(xd1, yd1); Point p2 = new Point(xd2, yd2); Point p3 = new Point(xd3, yd3); Point p4 = new Point(xd4, yd4); Point [] pt = new Point [5]; pt[0]=p1; pt[1]=p2; pt[2]=p3; pt[3]=p4; pt[4]=p1; Polygon pg = new Polygon(pt); if(pg.inside(pr1)||pg.inside(pr2)||pg.inside(pr3)||pg.inside(pr4)) { System.out.println("YES"); return; } LineSegment ld1 = new LineSegment(p1, p2); LineSegment ld2 = new LineSegment(p2, p3); LineSegment ld3 = new LineSegment(p3, p4); LineSegment ld4 = new LineSegment(p4, p1); Rectangle rec = new Rectangle(new Point(Math.min(Math.min(xr3,xr4),Math.min(xr1,xr2)), Math.min(Math.min(yr3,yr4),Math.min(yr1,yr2))), new Point(Math.max(Math.max(xr3,xr4),Math.max(xr1,xr2)), Math.max(Math.max(yr3,yr4),Math.max(yr1,yr2))) ); if(rec.contains(p1)||rec.contains(p2)||rec.contains(p3)||rec.contains(p4)) { System.out.println("YES"); return; } if(ld1.intersect(lr1)||ld1.intersect(lr3)||ld1.intersect(lr3)||ld1.intersect(lr4)) { System.out.println("YES"); return; } if(ld2.intersect(lr1)||ld2.intersect(lr3)||ld2.intersect(lr3)||ld2.intersect(lr4)) { System.out.println("YES"); return; } if(ld3.intersect(lr1)||ld3.intersect(lr3)||ld3.intersect(lr3)||ld3.intersect(lr4)) { System.out.println("YES"); return; } if(ld4.intersect(lr1)||ld4.intersect(lr3)||ld4.intersect(lr3)||ld4.intersect(lr4)) { System.out.println("YES"); return; } System.out.println("NO"); } public static class Polygon { // Cases to handle: collinear points, polygons with n < 3 static final double EPS = 1e-9; Point[] g; //first point = last point, counter-clockwise representation Polygon(Point[] o) { g = o; } double perimeter() { double sum = 0.0; for(int i = 0; i < g.length - 1; ++i) sum += g[i].dist(g[i+1]); return sum; } double area() //clockwise/anti-clockwise check, for convex/concave polygons { double area = 0.0; for(int i = 0; i < g.length - 1; ++i) area += g[i].x * g[i+1].y - g[i].y * g[i+1].x; return Math.abs(area) / 2.0; //negative value in case of clockwise } boolean inside(Point p) //for convex/concave polygons - winding number algorithm { double sum = 0.0; for(int i = 0; i < g.length - 1; ++i) { double angle = Point.angle(g[i], p, g[i+1]); if((Math.abs(angle) < EPS || Math.abs(angle - Math.PI) < EPS) && p.between(g[i], g[i+1])) return true; if(Point.ccw(p, g[i], g[i+1])) sum += angle; else sum -= angle; } return Math.abs(2 * Math.PI - Math.abs(sum)) < EPS; //abs makes it work for clockwise } /* * Another way if the polygon is convex * 1. Triangulate the poylgon through p * 2. Check if sum areas == poygon area * 3. Handle empty polygon */ Point centroid() //center of mass { double cx = 0.0, cy = 0.0; for(int i = 0; i < g.length - 1; i++) { double x1 = g[i].x, y1 = g[i].y; double x2 = g[i+1].x, y2 = g[i+1].y; double f = x1 * y2 - x2 * y1; cx += (x1 + x2) * f; cy += (y1 + y2) * f; } double area = area(); //remove abs cx /= 6.0 * area; cy /= 6.0 * area; return new Point(cx, cy); } } static class LineSegment { Point p, q; LineSegment(Point a, Point b) { p = a; q = b; } boolean intersect(LineSegment ls) { Line l1 = new Line(p, q), l2 = new Line(ls.p, ls.q); if(l1.parallel(l2)) { if(l1.same(l2)) return p.between(ls.p, ls.q) || q.between(ls.p, ls.q) || ls.p.between(p, q) || ls.q.between(p, q); return false; } Point c = l1.intersect(l2); return c.between(p, q) && c.between(ls.p, ls.q); } } static class Rectangle { static final double EPS = 1e-9; Point ll, ur; Rectangle(Point a, Point b) { ll = a; ur = b; } double area() { return (ur.x - ll.x) * (ur.y - ll.y); } boolean contains(Point p) { return p.x <= ur.x + EPS && p.x + EPS >= ll.x && p.y <= ur.y + EPS && p.y + EPS >= ll.y; } Rectangle intersect(Rectangle r) { Point ll = new Point(Math.max(this.ll.x, r.ll.x), Math.max(this.ll.y, r.ll.y)); Point ur = new Point(Math.min(this.ur.x, r.ur.x), Math.min(this.ur.y, r.ur.y)); if(Math.abs(ur.x - ll.x) > EPS && Math.abs(ur.y - ll.y) > EPS && this.contains(ll) && this.contains(ur) && r.contains(ll) && r.contains(ur)) return new Rectangle(ll, ur); return null; } } static class Line { static final double INF = 1e9, EPS = 1e-9; double a, b, c; Line(Point p, Point q) { if(Math.abs(p.x - q.x) < EPS) { a = 1; b = 0; c = -p.x; } else { a = (p.y - q.y) / (q.x - p.x); b = 1.0; c = -(a * p.x + p.y); } } Line(Point p, double m) { a = -m; b = 1; c = -(a * p.x + p.y); } boolean parallel(Line l) { return Math.abs(a - l.a) < EPS && Math.abs(b - l.b) < EPS; } boolean same(Line l) { return parallel(l) && Math.abs(c - l.c) < EPS; } Point intersect(Line l) { if(parallel(l)) return null; double x = (b * l.c - c * l.b) / (a * l.b - b * l.a); double y; if(Math.abs(b) < EPS) y = -l.a * x - l.c; else y = -a * x - c; return new Point(x, y); } Point closestPoint(Point p) { if(Math.abs(b) < EPS) return new Point(-c, p.y); if(Math.abs(a) < EPS) return new Point(p.x, -c); return intersect(new Line(p, 1 / a)); } } public static class Vector { double x, y; Vector(double a, double b) { x = a; y = b; } Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); } Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return x * v.y - y * v.x; } double norm2() { return x * x + y * y; } Vector reverse() { return new Vector(-x, -y); } Vector normalize() { double d = Math.sqrt(norm2()); return scale(1 / d); } } static class Point implements Comparable<Point>{ static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } Point rotate(double angle) { double c = Math.cos(angle), s = Math.sin(angle); return new Point(x * c - y * s, x * s + y * c); } // for integer points and rotation by 90 (counterclockwise) : swap x and y, negate x boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } //returns true if it is on the line defined by a and b //returns true if it is on the ray whose start point is a and passes through b // Another way: find closest point and calculate the distance between it and p } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public long nextlong() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); long res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
constant
994_C. Two Squares
CODEFORCES
/* Shubhang Verma */ import java.io.*; import java.math.*; import java.util.*; 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); mysolver mysol = new mysolver(); mysol.solve(in, out); out.close(); } } class node implements Comparable<node>{ int count; long value; public int compareTo(node t) { if(this.value == t.value) return 0; else if(this.value < t.value) return -1; else return 1; } } class mysolver { public long mod = 1000000007; int M,N; boolean bpm(boolean bpGraph[][], int u, boolean seen[], int matchR[]) { for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } int maxBPM(boolean bpGraph[][]) { int matchR[] = new int[N]; Arrays.fill(matchR,-1); int result = 0; for (int u = 0; u < M; u++) { boolean seen[] = new boolean[N]; if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } public void solve(InputReader in,OutputWriter out) { PrintWriter pout = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.readInt(); int m = in.readInt(); boolean eg[][] = new boolean[n][n]; for(int i=0;i<n;i++) { Arrays.fill(eg[i],false); } for(int i=0;i<m;i++) { int x = in.readInt()-1; int y = in.readInt()-1; eg[x][y] = true; } int minimum = Integer.MAX_VALUE; for(int i=0;i<n;i++) { int ct = 0; int addedges =0; if(eg[i][i] == false) { addedges++; } else { ct++; } for(int j=0;j<n;j++) { if(j!=i && eg[i][j]==false) { addedges++; } else if(j!=i && eg[i][j] == true) { ct++; } if(j!=i && eg[j][i]==false) { addedges++; } else if(j!=i && eg[j][i] == true) { ct++; } } //m - ct boolean row[] = new boolean[n]; boolean col[] = new boolean[n]; for(int j=0;j<n;j++) { row[j] = eg[i][j]; col[j] = eg[j][i]; eg[i][j] = false; eg[j][i] = false; } N = n; M = n; // for(int I=0;I<n;I++) // { // for(int J=0;J<n;J++) // { // System.out.print(eg[I][J]+" "); // } // System.out.println(); // } //System.out.println(); int matching = maxBPM(eg); //System.out.println(matching); addedges += n - 1 + m - ct - 2*matching; minimum = Math.min(minimum,addedges); for(int j=0;j<n;j++) { eg[i][j] = row[j]; eg[j][i] = col[j]; } } System.out.println(minimum); pout.close(); } } 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 isWhitespace(c); } public static boolean isWhitespace(int 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 close() { writer.close(); } public void printLine(int i) { writer.println(i); } } class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.sql.Time; import java.util.*; import java.math.BigInteger; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; public class Main{ void run(){ Locale.setDefault(Locale.US); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // boolean oj = true; try{ if( oj ){ sc = new FastScanner( new InputStreamReader(System.in ) ); out = new PrintWriter( new OutputStreamWriter(System.out) ); } else{ sc = new FastScanner(new FileReader("in.txt") ); // sc = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") ); out = new PrintWriter( new FileWriter("out.txt") ); } } catch (Exception e) { System.exit(-1); } long tB = System.currentTimeMillis(); solve(); if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 ); out.flush(); } class FastScanner{ BufferedReader br; StringTokenizer st = new StringTokenizer(""); FastScanner( InputStreamReader a ){ br = new BufferedReader(a); } FastScanner( FileReader a ){ br = new BufferedReader(a); } String next(){ while( !st.hasMoreTokens() ) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } return st.nextToken(); } String readLine(){ try { return br.readLine(); } catch (Exception e) { return null; } } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } } FastScanner sc; PrintWriter out; public static void main(String[] args){ new Main().run(); // new Thread( null, new Runnable() { // @Override // public void run() { // new Main().run(); // } // }, "LOL", 256L * 1024 * 1024 / 2 ).run(); // }, "LOL", 2000 * 1024 * 1024 ).run(); } void TLE(){ for(;;); } void MLE(){ int[][] adj = new int[1024*1024][]; for( int i = 0; i < adj.length; ++i ) adj[i] = new int[1024*1024]; } void exit( int val ){ out.flush(); System.exit(val); } ////////////////////////////////////////////////////////////////////////////////////////// int n, m; boolean[][] grid; ArrayList<Integer>[] gr; int c; int[] mt; boolean[] u; boolean try_kuhn( int v ){ if( u[v] ) return false; u[v] = true; for( int to : gr[v] ){ if( to == c || !grid[v][to] ) continue; if( mt[to]==-1 || try_kuhn(mt[to]) ){ mt[to] = v; return true; } } return false; } void solve(){ n = sc.nextInt(); m = sc.nextInt(); grid = new boolean[n+1][n+1]; gr = new ArrayList[n+1]; for( int v = 1; v <= n; ++v ) gr[v] = new ArrayList<Integer>(); for( int it = 0; it < m; ++it ){ int a = sc.nextInt(); int b = sc.nextInt(); grid[a][b] = true; gr[a].add(b); } int ans = Integer.MAX_VALUE; for( c = 1; c <= n; ++c ){ int curAns = 0; for( int v = 1; v <= n; ++v ) if( v != c ){ if( !grid[c][v] ) ++curAns; if( !grid[v][c] ) ++curAns; } if( !grid[c][c] ) ++curAns; mt = new int[n+1]; fill( mt, -1 ); for( int i = 1; i <= n; ++i ) if( i != c ){ u = new boolean[n+1]; try_kuhn(i); } int szMt = 0; for( int i = 1; i <= n; ++i ) if( mt[i] != -1 ) ++szMt; curAns += n - 1 - szMt; for( int a = 1; a <= n; ++a ){ for( int b = 1; b <= n; ++b ){ if( a==c || b==c || !grid[a][b] ) continue; if(!( a==mt[b] )) ++curAns; } } // out.printf( "%d %d\n", c, curAns ); ans = min( ans, curAns ); } out.println( ans ); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.LinkedList; public class D { static LinkedList<Integer>[] E; static int[] M; static boolean[] visited; static int n; static int center; public static boolean match(int x) { if (visited[x]) return false; visited[x] = true; for (int y : E[x]) if (y != center && (M[y] == -1 || match(M[y]))) { M[y] = x; return true; } return false; } public static int maxMatch() { int res = 0; Arrays.fill(M, -1); for (int i = 0; i < n; i++) { Arrays.fill(visited, false); if (i != center && match(i)) res++; } return res; } public static void main(String[] args) { InputReader in = new InputReader(System.in); n = in.readInt(); int m = in.readInt(); E = new LinkedList[n]; M = new int[n]; boolean[][] C = new boolean[n][n]; visited = new boolean[n]; for (int i = 0; i < n; i++) E[i] = new LinkedList<Integer>(); for (int i = 0; i < m; i++) { int x = in.readInt() - 1; int y = in.readInt() - 1; C[x][y] = true; E[x].add(y); } int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int res = 0; int all = 0; for (int j = 0; j < n; j++) if (j != i) { all += E[j].size(); if (!C[i][j]) res++; if (!C[j][i]) res++; else all--; } if (!C[i][i]) res++; center = i; int match = maxMatch(); res += (all - match) + (n - match - 1); min = Math.min(min, res); } System.out.println(min); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } 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; } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.Reader; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.List; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; /** * 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); int[] from = new int[m]; int[] to = new int[m]; for (int i = 0; i < m; i++) { from[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { KuhnMatchingGraph g = new KuhnMatchingGraph(n, n); int count = 0; for (int j = 0; j < m; j++) { if (from[j] != i && to[j] != i) { g.addEdge(from[j], to[j]); ++count; } } int cur = (n - 1 + count) - 2 * g.getMaximalMatching(); boolean[] a = new boolean[n]; boolean[] b = new boolean[n]; for (int j = 0; j < m; j++) { if (from[j] == i) { a[to[j]] = true; } if (to[j] == i) { b[from[j]] = true; } } for (int j = 0; j < n; j++) { if (j == i) { if (!a[j]) ++cur; } else { if (!a[j]) ++cur; if (!b[j]) ++cur; } } ans = Math.min(ans, cur); } out.println(ans); } } 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(); } } 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; } } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } } class KuhnMatchingGraph { int n; int m; List<Integer>[] edges; int[] p1; int[] p2; int[] was; int VER; public KuhnMatchingGraph(int n, int m) { this.n = n; this.m = m; edges = new ArrayList[n]; for (int i = 0; i < n; i++) { edges[i] = new ArrayList<Integer>(2); } } public void addEdge(int from, int to) { edges[from].add(to); } public int getMaximalMatching() { p1 = new int[n]; p2 = new int[m]; was = new int[n]; VER = 0; Arrays.fill(p1, -1); Arrays.fill(p2, -1); int answer = 0; for (int i = 0; i < n; i++) { for (int j : edges[i]) { if (p2[j] < 0) { p2[j] = i; p1[i] = j; answer++; break; } } } for (int i = 0; i < n; i++) { if (p1[i] >= 0) { continue; } VER++; if (dfs(i)) { answer++; } } return answer; } boolean dfs(int v) { if (was[v] == VER) { return false; } was[v] = VER; for (int i = 0; i < edges[v].size(); i++) { int e = edges[v].get(i); if (p2[e] < 0 || dfs(p2[e])) { p2[e] = v; p1[v] = e; return true; } } return false; } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.util.*; public class CF387D { static class A { ArrayList<Integer> list = new ArrayList<>(); int u, v, d; } static final int INF = Integer.MAX_VALUE; static boolean bfs(A[] aa, int n) { ArrayDeque<Integer> q = new ArrayDeque<>(); for (int u = 1; u <= n; u++) if (aa[u].v > 0) aa[u].d = INF; else { aa[u].d = 0; q.addLast(u); } aa[0].d = INF; while (!q.isEmpty()) { int u = q.removeFirst(); for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == INF) { aa[w].d = aa[u].d + 1; if (w == 0) return true; q.addLast(w); } } } return false; } static boolean dfs(A[] aa, int n, int u) { if (u == 0) return true; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == aa[u].d + 1 && dfs(aa, n, w)) { aa[u].v = v; aa[v].u = u; return true; } } aa[u].d = INF; return false; } static int matchings(A[] aa, int n) { int cnt = 0; while (bfs(aa, n)) for (int u = 1; u <= n; u++) if (aa[u].v == 0 && dfs(aa, n, u)) cnt++; return cnt; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] eu = new int[m]; int[] ev = new int[m]; for (int j = 0; j < m; j++) { st = new StringTokenizer(br.readLine()); eu[j] = Integer.parseInt(st.nextToken()); ev[j] = Integer.parseInt(st.nextToken()); } A[] aa = new A[n + 1]; int min = m + n * 3; for (int ctr = 1; ctr <= n; ctr++) { boolean loop = false; boolean[] ci = new boolean[n + 1]; boolean[] co = new boolean[n + 1]; for (int i = 0; i <= n; i++) aa[i] = new A(); int m_ = 0; for (int j = 0; j < m; j++) { int u = eu[j]; int v = ev[j]; if (u == ctr && v == ctr) loop = true; else if (u == ctr && v != ctr) ci[v] = true; else if (u != ctr && v == ctr) co[u] = true; else { aa[u].list.add(v); m_++; } } int cnt = loop ? 0 : 1; for (int i = 1; i <= n; i++) if (i != ctr) { if (!ci[i]) cnt++; if (!co[i]) cnt++; } int m2 = matchings(aa, n); cnt += (m_ - m2) + (n - 1 - m2); if (min > cnt) min = cnt; } System.out.println(min); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.awt.Point; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; public class R227_2_D { static ArrayList<Integer>[] graph; static int[] right, left; static boolean vis[]; public static boolean dfs(int node) { if (vis[node]) return false; vis[node] = true; for (int i = 0; i < graph[node].size(); i++) { int tmp = graph[node].get(i); if (right[tmp] == -1) { left[node] = tmp; right[tmp] = node; return true; } } for (int i = 0; i < graph[node].size(); i++) { int tmp = graph[node].get(i); if (dfs(right[tmp])) { left[node] = tmp; right[tmp] = node; return true; } } return false; } public static int getMaxMatch() { Arrays.fill(left, -1); Arrays.fill(right, -1); boolean done = false; while (!done) { done = true; Arrays.fill(vis, false); for (int i = 0; i < graph.length; i++) { if (left[i] == -1 && dfs(i)) { done = false; } } } int res = 0; for (int i = 0; i < left.length; i++) { res += (left[i] != -1 ? 1 : 0); } return res; } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int V = in.readInt(); int E = in.readInt(); Point[] edges = new Point[E]; for (int i = 0; i < edges.length; i++) { edges[i] = new Point(in.readInt() - 1, in.readInt() - 1); } int best = Integer.MAX_VALUE; for (int k = 0; k < V; k++) { int n = V - 1; graph = new ArrayList[n]; left = new int[n]; vis = new boolean[n]; right = new int[n]; for (int i = 0; i < graph.length; i++) { graph[i] = new ArrayList<Integer>(); } int center = 0; for (int i = 0; i < E; i++) { if (edges[i].x == k || edges[i].y == k) { center++; continue; } int src = edges[i].x > k ? edges[i].x - 1 : edges[i].x; int dst = edges[i].y > k ? edges[i].y - 1 : edges[i].y; graph[src].add(dst); } int matching = getMaxMatch(); int addToCenterEdges = 2 * V - 1 - center; int removed = E - center - matching; int added = n - matching; best = Math.min(best, added + removed + addToCenterEdges); } System.out.println(best); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } 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; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.util.*; public class CF387D { static class A { ArrayList<Integer> list = new ArrayList<>(); int u, v, d; } static int INF = Integer.MAX_VALUE; static boolean bfs(A[] aa, int n) { LinkedList<Integer> q = new LinkedList<>(); for (int u = 1; u <= n; u++) if (aa[u].v > 0) aa[u].d = INF; else { aa[u].d = 0; q.addLast(u); } aa[0].d = INF; while (!q.isEmpty()) { int u = q.removeFirst(); for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == INF) { aa[w].d = aa[u].d + 1; if (w == 0) return true; q.addLast(w); } } } return false; } static boolean dfs(A[] aa, int n, int u) { if (u == 0) return true; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == aa[u].d + 1 && dfs(aa, n, w)) { aa[u].v = v; aa[v].u = u; return true; } } aa[u].d = INF; return false; } static int matchings(A[] aa, int n) { int cnt = 0; while (bfs(aa, n)) for (int u = 1; u <= n; u++) if (aa[u].v == 0 && dfs(aa, n, u)) cnt++; return cnt; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] eu = new int[m]; int[] ev = new int[m]; for (int j = 0; j < m; j++) { st = new StringTokenizer(br.readLine()); eu[j] = Integer.parseInt(st.nextToken()); ev[j] = Integer.parseInt(st.nextToken()); } A[] aa = new A[n + 1]; int min = m + n * 3; for (int ctr = 1; ctr <= n; ctr++) { boolean loop = false; boolean[] ci = new boolean[n + 1]; boolean[] co = new boolean[n + 1]; for (int i = 0; i <= n; i++) aa[i] = new A(); int m_ = 0; for (int j = 0; j < m; j++) { int u = eu[j]; int v = ev[j]; if (u == ctr && v == ctr) loop = true; else if (u == ctr && v != ctr) ci[v] = true; else if (u != ctr && v == ctr) co[u] = true; else { aa[u].list.add(v); m_++; } } int cnt = loop ? 0 : 1; for (int i = 1; i <= n; i++) if (i != ctr) { if (!ci[i]) cnt++; if (!co[i]) cnt++; } int m2 = matchings(aa, n); cnt += (m_ - m2) + (n - 1 - m2); if (min > cnt) min = cnt; } System.out.println(min); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.LinkedList; import java.util.StringTokenizer; public class GeorgeAndInterestingGraph { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] edgeFrom = new int[M]; int[] edgeTo = new int[M]; for (int i = 0; i < M; i++) { edgeFrom[i] = sc.nextInt(); edgeTo[i] = sc.nextInt(); } int best = Integer.MAX_VALUE; boolean[][] adjMat = makeAdjMat(N, edgeFrom, edgeTo); for (int i = 0; i < N; i++) { boolean[][] mat = copyOfArray2d(adjMat); best = Math.min(best, count(mat, M, i)); } System.out.println(best); } public static boolean[][] copyOfArray2d(boolean[][] arr) { int N = arr.length; int M = arr[0].length; boolean[][] copy = new boolean[N][M]; for (int i = 0; i < N; i++) { System.arraycopy(arr[i], 0, copy[i], 0, M); } return copy; } public static int count(boolean[][] mat, int M, int center) { // int N = mat.length; // int M = mat[0].length; // // int centerConnect = (mat[center][center]) ? 0 : 1; // for (int i = 0; i < N; i++) { // if (i != center) { // if (!mat[i][center]) { // centerConnect++; // } // if (!mat[center][i]) { // centerConnect++; // } // } // mat[i][center] = false; // mat[center][i] = false; // } // // int[][] adjMat = new int[2 * N + 2][2 * N + 2]; // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // int idx = N + j; // adjMat[i][idx] = (mat[i][j]) ? 1 : 0; // } // } // int s = 2 * N; // int t = 2 * N + 1; // for (int i = 0; i < N; i++) { // adjMat[s][i] = 1; // } // for (int i = N; i < 2 * N; i++) { // adjMat[i][t] = 1; // } // // int matches = fordFulkerson(adjMat, s, t); // // return centerConnect + matches; int N = mat.length; // int M = mat[0].length; int cntWithI = (mat[center][center]) ? 1 : 0; for (int i = 0; i < N; i++) { if (i != center) { if (mat[i][center]) { cntWithI++; } if (mat[center][i]) { cntWithI++; } } mat[i][center] = false; mat[center][i] = false; } int other = M - cntWithI; // int centerConnect = (mat[center][center]) ? 0 : 1; // // for (int i = 0; i < N; i++) { // if (i != center) { // if (!mat[i][center]) { // centerConnect++; // } // if (!mat[center][i]) { // centerConnect++; // } // } // mat[i][center] = false; // mat[center][i] = false; // } int matches = bipartiteMatching(mat); return (2 * N - 1 - cntWithI + other - matches + N - 1 - matches); // return (centerConnect + N - 1 - matches); } public static boolean[][] makeAdjMat(int N, int[] edgeFrom, int[] edgeTo) { boolean[][] mat = new boolean[N][N]; for (int i = 0; i < edgeFrom.length; i++) { int from = edgeFrom[i] - 1; int to = edgeTo[i] - 1; mat[from][to] = true; } return mat; } /** * Returns true if there is a path from the source 's' to the sink 't' in the residual graph. * Also fills parent[] to store the path. * See here for more info: http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ */ public static boolean fordFulkersonHelper(int[][] resid, int s, int t, int[] parent) { int V = resid.length; boolean[] visited = new boolean[V]; LinkedList<Integer> q = new LinkedList<Integer>(); q.push(s); visited[s] = true; parent[s] = -1; while (!q.isEmpty()) { int u = q.pop(); for (int v = 0; v < V; v++) { if (!visited[v] && resid[u][v] > 0) { q.push(v); parent[v] = u; visited[v] = true; } } } return visited[t]; } /** * Returns the maximum flow from 's' to 't' in the given graph. * See here for more info: http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ */ public static int fordFulkerson(int[][] graph, int s, int t) { int V = graph.length; int[][] resid = new int[V][V]; int[] parent = new int[V]; int maxFlow = 0; for (int u = 0; u < V; u++) { for (int v = 0; v < V; v++) { resid[u][v] = graph[u][v]; } } while (fordFulkersonHelper(resid, s, t, parent)) { int pathFlow = Integer.MAX_VALUE; for (int v = t; v != s; v = parent[v]) { int u = parent[v]; pathFlow = Math.min(pathFlow, resid[u][v]); } for (int v = t; v != s; v = parent[v]) { int u = parent[v]; resid[u][v] -= pathFlow; resid[v][u] += pathFlow; } maxFlow += pathFlow; } return maxFlow; } /** * Returns true if a matching for vertex 'u' is possible. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static boolean bipartiteMatchingHelper(boolean[][] bpGraph, int u, boolean[] seen, int[] matchR) { int N = bpGraph[0].length; for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bipartiteMatchingHelper(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchIJ, int[] matchJI) { int ans = bipartiteMatching(bpGraph, matchJI); for (int i = 0; i < matchJI.length; i++) { matchIJ[i] = -1; } for (int j = 0; j < matchJI.length; j++) { int i = matchJI[j]; if (i >= 0) { matchIJ[i] = j; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchJI) { int M = bpGraph.length; int N = bpGraph[0].length; for (int i = 0; i < N; i++) { matchJI[i] = -1; } int ans = 0; for (int u = 0; u < M; u++) { boolean[] seen = new boolean[N]; if (bipartiteMatchingHelper(bpGraph, u, seen, matchJI)) { ans++; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Overload of the bipartiteMatching function without output parameters. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph) { int N = bpGraph[0].length; int[] matchJI = new int[N]; return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. */ public static int bipartiteMatching(int[][] intGraph) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchIJ, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchIJ, matchJI); } /** * Converts an integer adjacency matrix of 1's and 0's to a boolean adjacency matrix. * Useful with bipartiteMatching, which takes adjancency matrix of boolean[][] as input (instead of int[][]). */ public static boolean[][] intToBooleanAdjMat(int[][] mat) { int M = mat.length; int N = mat[0].length; boolean[][] bMat = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { bMat[i][j] = (mat[i][j] != 0); } } return bMat; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.util.ArrayList; import java.util.Scanner; public class Main { static ArrayList<Edge> graph; static ArrayList<ArrayList<Integer>> graphForKuhn; static int n, m, u = 0; static int mt[]; static int used[]; public static void main(String[] args) { formGraph(); System.out.println(getAnswer()); } static boolean kuhn(int start) { if (used[start] == u) return false; used[start] = u; for (int i=0; i< graphForKuhn.get(start).size(); i++) { int to = graphForKuhn.get(start).get(i); if (mt[to] == -1 || kuhn(mt[to])) { mt[to] = start; return true; } } return false; } private static int getAnswer() { int currentAnswer = Integer.MAX_VALUE; for (int cur= 0; cur<n; cur++) { int adj = 0, otheradj = 0, answer = 0; for (int j=0; j<n; j++) { graphForKuhn.get(j).clear(); mt[j] = -1; } for (int j=0; j<m; j++) { if (graph.get(j).from == cur || graph.get(j).to == cur) adj++; else { graphForKuhn.get(graph.get(j).from).add(graph.get(j).to); otheradj++; } } for (int j=0; j<n; j++) { u++; kuhn(j); } int tsz = 0; for (int j=0; j<n; j++) { if (mt[j] != -1) tsz++; } answer = 2*(n-1)+1-adj+otheradj-2*tsz+(n-1); currentAnswer = Math.min(answer, currentAnswer); } return currentAnswer; } private static void formGraph() { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); graph = new ArrayList<Edge>(m); for (int i=0; i<m; i++) { int x = in.nextInt(); int y = in.nextInt(); graph.add(new Edge(x-1, y-1)); } graphForKuhn = new ArrayList<ArrayList<Integer>>(n); for (int i=0; i<n; i++) graphForKuhn.add(new ArrayList<Integer>(n)); mt = new int[n]; used = new int[n]; in.close(); } } class Edge { int from; int to; public Edge(int from, int to) { this.from = from; this.to = to; } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @author Don Li */ public class GeorgeInterestingGraph { int N = 505; int INF = (int) 1e9; List<Integer>[] G = new List[N]; int[] match = new int[N]; int[] used = new int[N]; int cur = 0; { for (int i = 0; i < N; i++) G[i] = new ArrayList<>(1); } void solve() { int n = in.nextInt(), m = in.nextInt(); int[] fr = new int[m], to = new int[m]; for (int i = 0; i < m; i++) { fr[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } int ans = INF; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < n; j++) { G[j].clear(); match[j] = -1; } for (int j = 0; j < m; j++) { if (fr[j] == i || to[j] == i) { cnt++; } else { G[fr[j]].add(to[j]); } } int other = m - cnt; int max = 0; for (int j = 0; j < n; j++) { cur++; if (augment(j)) max++; } ans = Math.min(ans, 2 * (n - 1) + 1 - cnt + other - max + (n - 1) - max); } out.println(ans); } boolean augment(int u) { if (used[u] == cur) return false; used[u] = cur; for (int v : G[u]) { if (match[v] < 0 || augment(match[v])) { match[v] = u; return true; } } return false; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new GeorgeInterestingGraph().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int N = nextInt(); int M = nextInt(); boolean[][] graph = new boolean[N][N]; for (int i = 0; i < M; i++) { graph[nextInt()-1][nextInt()-1] = true; } int best = Integer.MAX_VALUE; for (int c = 0; c < N; c++) { int withC = 0; for (int i = 0; i < N; i++) { if (i == c) { if (graph[c][i]) withC++; } else { if (graph[c][i]) withC++; if (graph[i][c]) withC++; } } int notC = M - withC; List<Integer>[] g = new List[N]; for (int i = 0; i < N; i++) { g[i] = new ArrayList<Integer>(); } for (int i = 0; i < N; i++) { if (i == c) continue; for (int j = 0; j < N; j++) { if (j == c) continue; if (!graph[i][j]) continue; g[i].add(j); } } int glen = maxMatching(g, N); // int src = 2*N; // int dst = 2*N+1; // int[][] cap = new int[2*N+2][2*N+2]; // int[][] cost = new int[2*N+2][2*N+2]; // for (int i = 0; i < N; i++) { // cap[src][i] = 1; // cost[src][i] = 1; // cap[N+i][dst] = 1; // cost[N+i][dst] = 1; // } // for (int i = 0; i < N; i++) { // if (i == c) continue; // for (int j = 0; j < N; j++) { // if (j == c) continue; // if (!graph[i][j]) continue; // cap[i][N+j] = 1; // cost[i][N+j] = 1; // } // } // MinCostMaxFlow flow = new MinCostMaxFlow(); // int result[] = flow.getMaxFlow(cap, cost, src, dst); // int glen = result[0]; int need = (2*N-1 - withC) + (notC - glen) + (N - 1 - glen); best = Math.min(best, need); } out.println(best); } static boolean findPath(List<Integer>[] g, int u1, int[] matching, boolean[] vis) { vis[u1] = true; for (int v : g[u1]) { int u2 = matching[v]; if (u2 == -1 || !vis[u2] && findPath(g, u2, matching, vis)) { matching[v] = u1; return true; } } return false; } public static int maxMatching(List<Integer>[] g, int n2) { int n1 = g.length; int[] matching = new int[n2]; Arrays.fill(matching, -1); int matches = 0; for (int u = 0; u < n1; u++) { if (findPath(g, u, matching, new boolean[n1])) ++matches; } return matches; } /** * @param args */ public static void main(String[] args) { new D().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } 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 nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @author Don Li */ public class GeorgeInterestingGraph { int N = 505; int INF = (int) 1e9; List<Integer>[] G = new List[N]; int[] match = new int[N]; int[] used = new int[N]; int cur = 0; { for (int i = 0; i < N; i++) G[i] = new ArrayList<>(1); } void solve() { int n = in.nextInt(), m = in.nextInt(); int[] fr = new int[m], to = new int[m]; for (int i = 0; i < m; i++) { fr[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } int ans = INF; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < n; j++) { G[j].clear(); match[j] = -1; } for (int j = 0; j < m; j++) { if (fr[j] == i || to[j] == i) { cnt++; } else { G[fr[j]].add(to[j]); } } int other = m - cnt; int max = 0; for (int j = 0; j < n; j++) { cur++; augment(j); } for (int j = 0; j < n; j++) if (match[j] >= 0) max++; ans = Math.min(ans, 2 * (n - 1) + 1 - cnt + other - max + (n - 1) - max); } out.println(ans); } boolean augment(int u) { if (used[u] == cur) return false; used[u] = cur; for (int v : G[u]) { if (match[v] < 0 || augment(match[v])) { match[v] = u; return true; } } return false; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new GeorgeInterestingGraph().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
//Author: net12k44 import java.io.*; import java.util.*; public class Main{//} static PrintWriter out; static int c[][]; static int x[] , y[] , n; static int degIn[]; static ArrayList< ArrayList<Integer> >a = new ArrayList< ArrayList<Integer> >(); static int cnt = 0; static boolean b[]; private static boolean dfs(int i) { if (i == -1) return true; if (b[i]) return false; b[i] = true; for(Integer j : a.get(i) ) if ( dfs( y[j] ) ) { x[i] = j; y[j] = i; return true; } return false; } private static void find(int k) { int _cnt = -1; if (k>=0) { x[k] = k; y[k] = k; } while (_cnt != cnt) { _cnt = cnt; Arrays.fill( b , false ); if (k>=0) b[k] = true; for(int i = 0; i < n; ++i) if (x[i] == -1 && dfs(i) ) ++cnt; } if (k>=0) { x[k] = -1; y[k] = -1; } } public static void solve() { n = in.nextInt(); int m = in.nextInt(); b = new boolean[n]; c = new int [n][n]; degIn = new int[n]; x = new int[n]; y = new int[n]; Arrays.fill(x , -1); Arrays.fill(y , -1); for(int i = 0; i < n; ++i) a. add( new ArrayList< Integer > () ); while (m-- > 0) { int i = in.nextInt()-1 , j = in.nextInt()-1; a.get(i).add(j); degIn[j]++; c[i][j] = 1; } find(-1); int kq = Integer.MAX_VALUE; for(int k = 0; k < n; ++k) { if (x[k] != -1) {y[ x[k] ] = -1; x[k] = -1; cnt--; } if (y[k] != -1) {x[ y[k] ] = -1; y[k] = -1; cnt--; } find(k); int t = n*2 - 1 - a.get(k).size() - degIn[k] + c[k][k]; for(int i = 0; i < n; ++i) if (i!=k) t = t + a.get(i).size() - c[i][k]; t = t - cnt + (n-1) - cnt; if (kq > t) kq = t; } out.println(kq); } public static void main (String[] args) throws java.lang.Exception { long startTime = System.currentTimeMillis(); out = new PrintWriter(System.out); solve(); //out.println((String.format("%.2f",(double)(System.currentTimeMillis()-startTime)/1000))); out.close(); } static class in { static BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ) ; static StringTokenizer tokenizer = new StringTokenizer(""); static String next() { while ( !tokenizer.hasMoreTokens() ) try { tokenizer = new StringTokenizer( reader.readLine() ); } catch (IOException e){ throw new RuntimeException(e); } return tokenizer.nextToken(); } static int nextInt() { return Integer.parseInt( next() ); } static double nextDouble(){ return Double.parseDouble( next() ); } } ////////////////////////////////////////////////// }//
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class GeorgeAndInterestingGraph { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] edgeFrom = new int[M]; int[] edgeTo = new int[M]; for (int i = 0; i < M; i++) { edgeFrom[i] = sc.nextInt(); edgeTo[i] = sc.nextInt(); } int best = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { boolean[][] mat = makeAdjMat(N, edgeFrom, edgeTo); best = Math.min(best, count(mat, M, i)); } System.out.println(best); } public static int count(boolean[][] mat, int M, int center) { int N = mat.length; int centerCount = (mat[center][center]) ? 1 : 0; for (int i = 0; i < N; i++) { if (i != center) { if (mat[i][center]) { centerCount++; } if (mat[center][i]) { centerCount++; } } mat[i][center] = false; mat[center][i] = false; } int other = M - centerCount; int matches = bipartiteMatching(mat); return (2 * N - 1 - centerCount + other - matches + N - 1 - matches); } public static boolean[][] makeAdjMat(int N, int[] edgeFrom, int[] edgeTo) { boolean[][] mat = new boolean[N][N]; for (int i = 0; i < edgeFrom.length; i++) { int from = edgeFrom[i] - 1; int to = edgeTo[i] - 1; mat[from][to] = true; } return mat; } /** * Returns true if a matching for vertex 'u' is possible. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static boolean bipartiteMatchingHelper(boolean[][] bpGraph, int u, boolean[] seen, int[] matchR) { int N = bpGraph[0].length; for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bipartiteMatchingHelper(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchIJ, int[] matchJI) { int ans = bipartiteMatching(bpGraph, matchJI); for (int i = 0; i < matchJI.length; i++) { matchIJ[i] = -1; } for (int j = 0; j < matchJI.length; j++) { int i = matchJI[j]; if (i >= 0) { matchIJ[i] = j; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchJI) { int M = bpGraph.length; int N = bpGraph[0].length; for (int i = 0; i < N; i++) { matchJI[i] = -1; } int ans = 0; for (int u = 0; u < M; u++) { boolean[] seen = new boolean[N]; if (bipartiteMatchingHelper(bpGraph, u, seen, matchJI)) { ans++; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Overload of the bipartiteMatching function without output parameters. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph) { int N = bpGraph[0].length; int[] matchJI = new int[N]; return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. */ public static int bipartiteMatching(int[][] intGraph) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchIJ, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchIJ, matchJI); } /** * Converts an integer adjacency matrix of 1's and 0's to a boolean adjacency matrix. * Useful with bipartiteMatching, which takes adjancency matrix of boolean[][] as input (instead of int[][]). */ public static boolean[][] intToBooleanAdjMat(int[][] mat) { int M = mat.length; int N = mat[0].length; boolean[][] bMat = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { bMat[i][j] = (mat[i][j] != 0); } } return bMat; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class GeorgeAndInterestingGraph { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] edgeFrom = new int[M]; int[] edgeTo = new int[M]; for (int i = 0; i < M; i++) { edgeFrom[i] = sc.nextInt(); edgeTo[i] = sc.nextInt(); } int best = Integer.MAX_VALUE; boolean[][] adjMat = makeAdjMat(N, edgeFrom, edgeTo); for (int i = 0; i < N; i++) { boolean[][] mat = copyOfArray2d(adjMat); best = Math.min(best, count(mat, M, i)); } System.out.println(best); } public static boolean[][] copyOfArray2d(boolean[][] arr) { int N = arr.length; int M = arr[0].length; boolean[][] copy = new boolean[N][M]; for (int i = 0; i < N; i++) { System.arraycopy(arr[i], 0, copy[i], 0, M); } return copy; } public static int count(boolean[][] mat, int M, int center) { int N = mat.length; int centerCount = (mat[center][center]) ? 1 : 0; for (int i = 0; i < N; i++) { if (i != center) { if (mat[i][center]) { centerCount++; } if (mat[center][i]) { centerCount++; } } mat[i][center] = false; mat[center][i] = false; } int other = M - centerCount; int matches = bipartiteMatching(mat); return (2 * N - 1 - centerCount + other - matches + N - 1 - matches); } public static boolean[][] makeAdjMat(int N, int[] edgeFrom, int[] edgeTo) { boolean[][] mat = new boolean[N][N]; for (int i = 0; i < edgeFrom.length; i++) { int from = edgeFrom[i] - 1; int to = edgeTo[i] - 1; mat[from][to] = true; } return mat; } /** * Returns true if a matching for vertex 'u' is possible. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static boolean bipartiteMatchingHelper(boolean[][] bpGraph, int u, boolean[] seen, int[] matchR) { int N = bpGraph[0].length; for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bipartiteMatchingHelper(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchIJ, int[] matchJI) { int ans = bipartiteMatching(bpGraph, matchJI); for (int i = 0; i < matchJI.length; i++) { matchIJ[i] = -1; } for (int j = 0; j < matchJI.length; j++) { int i = matchJI[j]; if (i >= 0) { matchIJ[i] = j; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchJI) { int M = bpGraph.length; int N = bpGraph[0].length; for (int i = 0; i < N; i++) { matchJI[i] = -1; } int ans = 0; for (int u = 0; u < M; u++) { boolean[] seen = new boolean[N]; if (bipartiteMatchingHelper(bpGraph, u, seen, matchJI)) { ans++; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Overload of the bipartiteMatching function without output parameters. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph) { int N = bpGraph[0].length; int[] matchJI = new int[N]; return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. */ public static int bipartiteMatching(int[][] intGraph) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchIJ, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchIJ, matchJI); } /** * Converts an integer adjacency matrix of 1's and 0's to a boolean adjacency matrix. * Useful with bipartiteMatching, which takes adjancency matrix of boolean[][] as input (instead of int[][]). */ public static boolean[][] intToBooleanAdjMat(int[][] mat) { int M = mat.length; int N = mat[0].length; boolean[][] bMat = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { bMat[i][j] = (mat[i][j] != 0); } } return bMat; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } @SuppressWarnings("unchecked") void solve() throws IOException { final int n = nextInt(); int m = nextInt(); int[] from = new int[m]; int[] to = new int[m]; for(int i = 0; i < m; i++) { from[i] = nextInt(); to[i] = nextInt(); } int ans = solve(n, m, from, to); writer.println(ans); writer.close(); } private int solve(final int n, int m, int[] from, int[] to) { final List<List<Integer>> g = new ArrayList<>(); final List<List<Integer>> rg = new ArrayList<>(); for(int i = 0; i <= n; i++) { g.add(new ArrayList<Integer>()); rg.add(new ArrayList<Integer>()); } int[] c = new int[n + 1]; int[] loop = new int[n + 1]; for(int i = 0; i < m; i++) { int u = from[i]; int v = to[i]; g.get(u).add(v); rg.get(v).add(u); c[u]++; c[v]++; if(u == v) { loop[u]++; } } class Utils { int[] prev = new int[n + 1]; int[] next = new int[n + 1]; int[] used = new int[n + 1]; int mark; int forbidden; int maxMatch() { maxMatch = 0; for(int i = 1; i <= n; i++) { mark = i; if(findPath(i)) { maxMatch++; } } return maxMatch; } boolean findPath(int u) { if(u == forbidden) { return false; } used[u] = mark; for (int v : g.get(u)) { if(v == forbidden) { continue; } if(prev[v] == 0 || (used[prev[v]] != mark && findPath(prev[v]))) { prev[v] = u; next[u] = v; return true; } } return false; } int maxMatch = 0; void amend(int u) { // Arrays.fill(used, false); if(findPath(u)) { maxMatch++; } } void cancel(int u) { forbidden = u; int v = next[u]; if(v != 0) { maxMatch--; prev[v] = 0; next[u] = 0; for (int i : rg.get(v)) { if(next[i] == 0) { amend(i); } } // amend(v); } if(prev[u] != 0) { maxMatch--; amend(prev[u]); prev[u] = 0; } } } // Utils utils = new Utils(); // for(int i = 1; i <= n; i++) { // utils.amend(i); // } int ans = Integer.MAX_VALUE; for(int i = 1; i <= n; i++) { // utils.cancel(i); // utils.amend(i - 1); Utils utils = new Utils(); utils.forbidden = i; utils.maxMatch(); ans = Math.min(ans, (2 * n - 1 - c[i] + loop[i]) + (m - c[i] + loop[i] - utils.maxMatch) + (n - 1 - utils.maxMatch)); } return ans; } void test() { final int N = 4; final int[] ef = new int[N * N]; final int[] et = new int[N * N]; for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) { ef[(i - 1) * N + j - 1] = i; et[(i - 1) * N + j - 1] = j; } } List<Integer> good = new ArrayList<>(); for(int mask = 0; mask < 1 << N * N; mask++) { int[] in = new int[N + 1]; int[] out = new int[N + 1]; for(int i = 0; i < N * N; i++) { if((mask >> i) % 2 == 1) { out[ef[i]]++; in[et[i]]++; } } boolean ok = false; for(int i = 1; i <= N; i++) { if(in[i] == N && out[i] == N) { in[i] = 2; out[i] = 2; ok = true; break; } } for(int i = 1; i <= N; i++) { if(in[i] != 2 || out[i] != 2) { ok = false; } } if(ok) { good.add(mask); } } System.out.println("good graphs count: " + good.size()); for (int mask : good) { int m = Integer.bitCount(mask); int[] from = new int[m]; int[] to = new int[m]; int index = 0; for(int i = 0; i < N * N; i++) { if((mask >> i) % 2 == 1) { from[index] = ef[i]; to[index] = et[i]; index++; } } if(solve(N, m, from, to) != 0) { writer.println(N + " " + m); for(int i = 0; i < m; i++) { writer.println(from[i] + " " + to[i]); } writer.close(); return; } } for(int mask = 0; mask < 1 << N * N; mask++) { int optimal = Integer.MAX_VALUE; for (Integer i : good) { optimal = Math.min(optimal, Integer.bitCount(i ^ mask)); } int m = Integer.bitCount(mask); int[] from = new int[m]; int[] to = new int[m]; int index = 0; for(int i = 0; i < N * N; i++) { if((mask >> i) % 2 == 1) { from[index] = ef[i]; to[index] = et[i]; index++; } } final int fast = solve(N, m, from, to); if(optimal != fast) { System.out.println("fast = " + fast + ", optimal = " + optimal); writer.println(N + " " + m); for(int i = 0; i < m; i++) { writer.println(from[i] + " " + to[i]); } writer.close(); return; } } } public static void main(String[] args) throws IOException { new D().solve(); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.System.out; import static java.util.Collections.*; import java.io.*; import java.math.*; import java.util.*; public class Main { static boolean LOCAL = System.getSecurityManager() == null; Scanner in = new Scanner(System.in); private int[] B; private int[] A; private int n; private int m; void run() { n = in.nextInt(); m = in.nextInt(); A = new int[m]; B = new int[m]; for (int i = 0; i < m; i++) { A[i] = in.nextInt() - 1; B[i] = in.nextInt() - 1; } int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { ans = min(ans, solve(i)); } out.println(ans); } int solve(int x) { int ans = 3 * (n - 1) + 1 + m; V[] vs = new V[n * 2]; for (int i = 0; i < vs.length; i++) vs[i] = new V(); for (int i = 0; i < m; i++) { if (A[i] == x || B[i] == x) ans -= 2; else vs[A[i]].connect(vs[n + B[i]]); } return ans - 2 * bipartiteMatching(vs); } class V extends ArrayList<V> { V pair; boolean used; void connect(V v) { add(v); v.add(this); } } int bipartiteMatching(V[] vs) { int match = 0; for (V v : vs) if (v.pair == null) { for (V u : vs) u.used = false; if (dfs(v)) match++; } return match; } boolean dfs(V v) { v.used = true; for (V u : v) { V w = u.pair; if (w == null || !w.used && dfs(w)) { v.pair = u; u.pair = v; return true; } } return false; } void debug(Object... os) { System.err.println(deepToString(os)); } public static void main(String[] args) { if (LOCAL) { try { System.setIn(new FileInputStream("./../../in.txt")); // System.setOut(new PrintStream("./../../out")); } catch (Throwable e) { LOCAL = false; } } long start = 0; if (LOCAL) start = System.nanoTime(); new Main().run(); if (LOCAL) System.err.printf("[Time : %.6f s]%n", (System.nanoTime() - start) * 1e-9); } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } void eat(String s) { st = new StringTokenizer(s); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } String next() { hasNext(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } @SuppressWarnings("unchecked") void solve() throws IOException { final int n = nextInt(); int m = nextInt(); int[] from = new int[m]; int[] to = new int[m]; for(int i = 0; i < m; i++) { from[i] = nextInt(); to[i] = nextInt(); } int ans = solve(n, m, from, to); writer.println(ans); writer.close(); } private int solve(final int n, int m, int[] from, int[] to) { final List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i <= n; i++) { g.add(new ArrayList<Integer>()); } int[] c = new int[n + 1]; int[] loop = new int[n + 1]; for(int i = 0; i < m; i++) { int u = from[i]; int v = to[i]; g.get(u).add(v); c[u]++; c[v]++; if(u == v) { loop[u]++; } } class Utils { int[] prev = new int[n + 1]; int[] used = new int[n + 1]; int mark; int forbidden; int maxMatch() { maxMatch = 0; for(int i = 1; i <= n; i++) { mark = i; if(findPath(i)) { maxMatch++; } } return maxMatch; } boolean findPath(int u) { if(u == forbidden) { return false; } used[u] = mark; for (int v : g.get(u)) { if(v == forbidden) { continue; } if(prev[v] == 0 || (used[prev[v]] != mark && findPath(prev[v]))) { prev[v] = u; return true; } } return false; } int maxMatch = 0; } int ans = Integer.MAX_VALUE; for(int i = 1; i <= n; i++) { Utils utils = new Utils(); utils.forbidden = i; utils.maxMatch(); ans = Math.min(ans, (2 * n - 1 - c[i] + loop[i]) + (m - c[i] + loop[i] - utils.maxMatch) + (n - 1 - utils.maxMatch)); } return ans; } public static void main(String[] args) throws IOException { new D().solve(); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.sql.Time; import java.util.*; import java.math.BigInteger; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; public class Main{ void run(){ Locale.setDefault(Locale.US); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // boolean oj = true; try{ if( oj ){ sc = new FastScanner( new InputStreamReader(System.in ) ); out = new PrintWriter( new OutputStreamWriter(System.out) ); } else{ sc = new FastScanner(new FileReader("in.txt") ); // sc = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") ); out = new PrintWriter( new FileWriter("out.txt") ); } } catch (Exception e) { System.exit(-1); } long tB = System.currentTimeMillis(); solve(); if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 ); out.flush(); } class FastScanner{ BufferedReader br; StringTokenizer st = new StringTokenizer(""); FastScanner( InputStreamReader a ){ br = new BufferedReader(a); } FastScanner( FileReader a ){ br = new BufferedReader(a); } String next(){ while( !st.hasMoreTokens() ) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } return st.nextToken(); } String readLine(){ try { return br.readLine(); } catch (Exception e) { return null; } } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } } FastScanner sc; PrintWriter out; public static void main(String[] args){ new Main().run(); // new Thread( null, new Runnable() { // @Override // public void run() { // new Main().run(); // } // }, "LOL", 256L * 1024 * 1024 / 2 ).run(); // }, "LOL", 2000 * 1024 * 1024 ).run(); } void TLE(){ for(;;); } void MLE(){ int[][] adj = new int[1024*1024][]; for( int i = 0; i < adj.length; ++i ) adj[i] = new int[1024*1024]; } void exit( int val ){ out.flush(); System.exit(val); } ////////////////////////////////////////////////////////////////////////////////////////// int n, m; boolean[][] grid; ArrayList<Integer>[] gr; int c; int[] mt; boolean[] u; boolean try_kuhn( int v ){ if( u[v] ) return false; u[v] = true; for( int to : gr[v] ){ if( to == c || !grid[v][to] ) continue; if( mt[to]==-1 || try_kuhn(mt[to]) ){ mt[to] = v; return true; } } return false; } void solve(){ n = sc.nextInt(); m = sc.nextInt(); grid = new boolean[n+1][n+1]; gr = new ArrayList[n+1]; for( int v = 1; v <= n; ++v ) gr[v] = new ArrayList<Integer>(); for( int it = 0; it < m; ++it ){ int a = sc.nextInt(); int b = sc.nextInt(); grid[a][b] = true; gr[a].add(b); } int ans = Integer.MAX_VALUE; for( c = 1; c <= n; ++c ){ int curAns = 0; for( int v = 1; v <= n; ++v ) if( v != c ){ if( !grid[c][v] ) ++curAns; if( !grid[v][c] ) ++curAns; } if( !grid[c][c] ) ++curAns; mt = new int[n+1]; fill( mt, -1 ); for( int i = 1; i <= n; ++i ) if( i != c ){ u = new boolean[n+1]; try_kuhn(i); } int szMt = 0; for( int i = 1; i <= n; ++i ) if( mt[i] != -1 ) ++szMt; curAns += n - 1 - szMt; for( int a = 1; a <= n; ++a ){ for( int b : gr[a] ){ if( a==c || b==c || !grid[a][b] ) continue; if(!( a==mt[b] )) ++curAns; } } // out.printf( "%d %d\n", c, curAns ); ans = min( ans, curAns ); } out.println( ans ); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
//package round227; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] from = new int[m]; int[] to = new int[m]; for(int i = 0;i < m;i++){ from[i] = ni()-1; to[i] = ni()-1; } int[] nfrom = new int[m]; int[] nto = new int[m]; int min = 999999999; for(int i = 0;i < n;i++){ int p = 0; for(int j = 0;j < m;j++){ if(from[j] != i && to[j] != i){ nfrom[p] = from[j]; nto[p] = to[j]; p++; } } int[][] g = packD(n, nfrom, nto, p); int mat = doBipartiteMatchingHKNoRec(g, n); int ch = p - mat + (n-1-mat); ch += 2*n-1 - (m - p); min = Math.min(min, ch); } out.println(min); } public static int doBipartiteMatchingHKNoRec(int[][] g, int m) { int n = g.length; if(n == 0)return 0; int[] from = new int[m]; int[] to = new int[n]; Arrays.fill(to, -1); Arrays.fill(from, n); int[] d = new int[n+1]; int mat = 0; int[] stack = new int[n+1]; int[] adjind = new int[n+1]; while(true){ Arrays.fill(d, -1); int[] q = new int[n]; int r = 0; for(int i = 0;i < n;i++){ if(to[i] == -1){ d[i] = 0; q[r++] = i; } } for(int p = 0;p < r;p++) { int cur = q[p]; for(int adj : g[cur]){ int nex = from[adj]; if(d[nex] == -1) { if(nex != n)q[r++] = nex; d[nex] = d[cur] + 1; } } } if(d[n] == -1)break; for(int i = 0;i < n;i++){ if(to[i] == -1){ int sp = 1; stack[0] = i; adjind[0] = 0; boolean prevB = false; outer: while(sp >= 1){ int cur = stack[sp-1]; if(cur == n){ prevB = true; sp--; continue; } for(;adjind[sp-1] < 2*g[cur].length;){ int adj = g[cur][adjind[sp-1]/2]; if(adjind[sp-1] % 2 == 0){ int nex = from[adj]; if(d[nex] == d[cur] + 1){ stack[sp] = nex; adjind[sp] = 0; adjind[sp-1]++; sp++; continue outer; }else{ adjind[sp-1]+=2; } }else{ if(prevB){ to[cur] = adj; from[adj] = cur; prevB = true; sp--; continue outer; } adjind[sp-1]++; } } d[cur] = -1; prevB = false; sp--; } if(prevB)mat++; } } } return mat; } public static int[][] packD(int n, int[] from, int[] to, int sup) { int[][] g = new int[n][]; int[] p = new int[n]; for(int i = 0;i < sup;i++)p[from[i]]++; for(int i = 0;i < n;i++)g[i] = new int[p[i]]; for(int i = 0;i < sup;i++){ g[from[i]][--p[from[i]]] = to[i]; } return g; } void run() throws Exception { // int n = 500, m = 1000; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // boolean[][] g = new boolean[n][n]; // for(int i = 0;i < m;i++){ // while(true){ // int r = gen.nextInt(n); // int c = gen.nextInt(n); // if(!g[r][c]){ // g[r][c] = true; // break; // } // } // } // for(int i = 0;i < n;i++){ // for(int j = 0;j < n;j++){ // if(g[i][j]){ // sb.append((i+1) + " "); // sb.append((j+1) + " "); // } // } // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private 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++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { 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 * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int 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 * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.util.*; public class CF387D { static class A { ArrayList<Integer> list = new ArrayList<>(); int u, v, d; } static int INF = Integer.MAX_VALUE; static boolean bfs(A[] aa, int n) { LinkedList<Integer> queue = new LinkedList<>(); for (int u = 1; u <= n; u++) if (aa[u].v > 0) aa[u].d = INF; else { aa[u].d = 0; queue.addLast(u); } aa[0].d = INF; while (!queue.isEmpty()) { int u = queue.removeFirst(); if (aa[u].d + 1 == aa[0].d) break; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == INF) { aa[w].d = aa[u].d + 1; queue.addLast(w); } } } return aa[0].d != INF; } static boolean dfs(A[] aa, int n, int u) { if (u == 0) return true; for (int v : aa[u].list) { int w = aa[v].u; if (aa[w].d == aa[u].d + 1 && dfs(aa, n, w)) { aa[u].v = v; aa[v].u = u; return true; } } aa[u].d = INF; return false; } static int matchings(A[] aa, int n) { int cnt = 0; while (bfs(aa, n)) for (int u = 1; u <= n; u++) if (aa[u].v == 0 && dfs(aa, n, u)) cnt++; return cnt; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] eu = new int[m]; int[] ev = new int[m]; for (int j = 0; j < m; j++) { st = new StringTokenizer(br.readLine()); eu[j] = Integer.parseInt(st.nextToken()); ev[j] = Integer.parseInt(st.nextToken()); } A[] aa = new A[n + 1]; int min = m + n * 3; for (int ctr = 1; ctr <= n; ctr++) { boolean loop = false; boolean[] ci = new boolean[n + 1]; boolean[] co = new boolean[n + 1]; for (int i = 0; i <= n; i++) aa[i] = new A(); int m_ = 0; for (int j = 0; j < m; j++) { int u = eu[j]; int v = ev[j]; if (u == ctr && v == ctr) loop = true; else if (u == ctr && v != ctr) ci[v] = true; else if (u != ctr && v == ctr) co[u] = true; else { aa[u].list.add(v); m_++; } } int cnt = loop ? 0 : 1; for (int i = 1; i <= n; i++) if (i != ctr) { if (!ci[i]) cnt++; if (!co[i]) cnt++; } int m2 = matchings(aa, n); cnt += (m_ - m2) + (n - 1 - m2); if (min > cnt) min = cnt; } System.out.println(min); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.util.*; public class CF { class W implements Comparable<W> { int id, sz; W(int id, int sz) { this.id = id; this.sz = sz; } @Override public int compareTo(W o) { return -Integer.compare(sz, o.sz); } } int[] left; int center; boolean[] used; boolean go(int v) { if (used[v]) return false; used[v] = true; for (int i = 0; i < g[v].size(); ++i) { int to = g[v].get(i); if (to == center) continue; if (left[to] == -1 || go(left[to])) { left[to] = v; return true; } } return false; } ArrayList<Integer>[] g; void solve() { int n = in.nextInt(); int m = in.nextInt(); used = new boolean[n]; g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { g[in.nextInt() - 1].add(in.nextInt() - 1); } long st = System.currentTimeMillis(); int ans = Integer.MAX_VALUE; W[] a = new W[n]; for (int i = 0; i < n; i++) { a[i] = new W(i, g[i].size()); } left = new int[n]; Arrays.sort(a); for (int centerId = 0; centerId < n; centerId++) { center = a[centerId].id; if (System.currentTimeMillis() - st > 800) break; int cost = n - g[center].size(); Arrays.fill(left, -1); for (int i = 0; i < n; i++) if (i != center) { boolean has = false; for (int j = 0; j < g[i].size(); j++) { if (g[i].get(j) == center) has = true; } Arrays.fill(used, false); if (!go(i)) { if (has) { cost += g[i].size(); } else { cost += g[i].size() + 2; } } else { if (has) { cost += g[i].size() - 2; } else { cost += g[i].size(); } } } ans = Math.min(ans, cost); } out.println(ans); } FastScaner in; PrintWriter out; void run() { in = new FastScaner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void runWithFiles() { in = new FastScaner(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } public static void main(String[] args) { Locale.setDefault(Locale.US); new CF().run(); } class FastScaner { BufferedReader br; StringTokenizer st; FastScaner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } FastScaner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.LinkedList; import java.util.StringTokenizer; public class GeorgeAndInterestingGraph { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int[] edgeFrom = new int[M]; int[] edgeTo = new int[M]; for (int i = 0; i < M; i++) { edgeFrom[i] = sc.nextInt(); edgeTo[i] = sc.nextInt(); } int best = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { boolean[][] mat = makeAdjMat(N, edgeFrom, edgeTo); best = Math.min(best, count(mat, i, M)); } System.out.println(best); } public static int count(boolean[][] mat, int center, int M) { // int N = mat.length; // int M = mat[0].length; // // int centerConnect = (mat[center][center]) ? 0 : 1; // for (int i = 0; i < N; i++) { // if (i != center) { // if (!mat[i][center]) { // centerConnect++; // } // if (!mat[center][i]) { // centerConnect++; // } // } // mat[i][center] = false; // mat[center][i] = false; // } // // int[][] adjMat = new int[2 * N + 2][2 * N + 2]; // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // int idx = N + j; // adjMat[i][idx] = (mat[i][j]) ? 1 : 0; // } // } // int s = 2 * N; // int t = 2 * N + 1; // for (int i = 0; i < N; i++) { // adjMat[s][i] = 1; // } // for (int i = N; i < 2 * N; i++) { // adjMat[i][t] = 1; // } // // int matches = fordFulkerson(adjMat, s, t); // // return centerConnect + matches; int N = mat.length; // int M = mat[0].length; int cntWithI = (mat[center][center]) ? 1 : 0; for (int i = 0; i < N; i++) { if (i != center) { if (mat[i][center]) { cntWithI++; } if (mat[center][i]) { cntWithI++; } } mat[i][center] = false; mat[center][i] = false; } int other = M - cntWithI; // int centerConnect = (mat[center][center]) ? 0 : 1; // // for (int i = 0; i < N; i++) { // if (i != center) { // if (!mat[i][center]) { // centerConnect++; // } // if (!mat[center][i]) { // centerConnect++; // } // } // mat[i][center] = false; // mat[center][i] = false; // } int matches = bipartiteMatching(mat); return (2 * N - 1 - cntWithI + other - matches + N - 1 - matches); // return (centerConnect + N - 1 - matches); } public static boolean[][] makeAdjMat(int N, int[] edgeFrom, int[] edgeTo) { boolean[][] mat = new boolean[N][N]; for (int i = 0; i < edgeFrom.length; i++) { int from = edgeFrom[i] - 1; int to = edgeTo[i] - 1; mat[from][to] = true; } return mat; } /** * Returns true if there is a path from the source 's' to the sink 't' in the residual graph. * Also fills parent[] to store the path. * See here for more info: http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ */ public static boolean fordFulkersonHelper(int[][] resid, int s, int t, int[] parent) { int V = resid.length; boolean[] visited = new boolean[V]; LinkedList<Integer> q = new LinkedList<Integer>(); q.push(s); visited[s] = true; parent[s] = -1; while (!q.isEmpty()) { int u = q.pop(); for (int v = 0; v < V; v++) { if (!visited[v] && resid[u][v] > 0) { q.push(v); parent[v] = u; visited[v] = true; } } } return visited[t]; } /** * Returns the maximum flow from 's' to 't' in the given graph. * See here for more info: http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ */ public static int fordFulkerson(int[][] graph, int s, int t) { int V = graph.length; int[][] resid = new int[V][V]; int[] parent = new int[V]; int maxFlow = 0; for (int u = 0; u < V; u++) { for (int v = 0; v < V; v++) { resid[u][v] = graph[u][v]; } } while (fordFulkersonHelper(resid, s, t, parent)) { int pathFlow = Integer.MAX_VALUE; for (int v = t; v != s; v = parent[v]) { int u = parent[v]; pathFlow = Math.min(pathFlow, resid[u][v]); } for (int v = t; v != s; v = parent[v]) { int u = parent[v]; resid[u][v] -= pathFlow; resid[v][u] += pathFlow; } maxFlow += pathFlow; } return maxFlow; } /** * Returns true if a matching for vertex 'u' is possible. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static boolean bipartiteMatchingHelper(boolean[][] bpGraph, int u, boolean[] seen, int[] matchR) { int N = bpGraph[0].length; for (int v = 0; v < N; v++) { if (bpGraph[u][v] && !seen[v]) { seen[v] = true; if (matchR[v] < 0 || bipartiteMatchingHelper(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchIJ, int[] matchJI) { int ans = bipartiteMatching(bpGraph, matchJI); for (int i = 0; i < matchJI.length; i++) { matchIJ[i] = -1; } for (int j = 0; j < matchJI.length; j++) { int i = matchJI[j]; if (i >= 0) { matchIJ[i] = j; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Note: bpGraph[i][j] = true if there is an edge from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph, int[] matchJI) { int M = bpGraph.length; int N = bpGraph[0].length; for (int i = 0; i < N; i++) { matchJI[i] = -1; } int ans = 0; for (int u = 0; u < M; u++) { boolean[] seen = new boolean[N]; if (bipartiteMatchingHelper(bpGraph, u, seen, matchJI)) { ans++; } } return ans; } /** * Returns the maximum bipartite matching from an an adjacency matrix. * Overload of the bipartiteMatching function without output parameters. * See here for more info: http://www.geeksforgeeks.org/maximum-bipartite-matching/ */ public static int bipartiteMatching(boolean[][] bpGraph) { int N = bpGraph[0].length; int[] matchJI = new int[N]; return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. */ public static int bipartiteMatching(int[][] intGraph) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchJI); } /** * Overload of the bipartiteMatching function taking an adjacency matrix of int[][] instead of boolean[][]. * Note: matchIJ (array of length M) is an output variable containing the matchings, such that matchIJ[i] = j means that there is a match from i to j. * Note: matchJI (array of length N) is an output variable containing the matchings, such that matchJI[j] = i means that there is a match from i to j. */ public static int bipartiteMatching(int[][] intGraph, int[] matchIJ, int[] matchJI) { boolean[][] bpGraph = intToBooleanAdjMat(intGraph); return bipartiteMatching(bpGraph, matchIJ, matchJI); } /** * Converts an integer adjacency matrix of 1's and 0's to a boolean adjacency matrix. * Useful with bipartiteMatching, which takes adjancency matrix of boolean[][] as input (instead of int[][]). */ public static boolean[][] intToBooleanAdjMat(int[][] mat) { int M = mat.length; int N = mat[0].length; boolean[][] bMat = new boolean[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { bMat[i][j] = (mat[i][j] != 0); } } return bMat; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(final String[] args) throws IOException { try(Scanner scan = new Scanner(System.in); PrintWriter print = new PrintWriter(System.out)) { final int n = scan.nextInt(); final int m = scan.nextInt(); final Pair<Integer, Integer>[] arcs = new Pair[m]; for(int k = 0; k < m; ++k) { int i = scan.nextInt(); int j = scan.nextInt(); --i; --j; arcs[k] = new Pair(i, j); } print.println(calcMinNumStepsToCenterPermGraph(new DirectedGraph(n, arcs))); } } public static int calcMinNumStepsToCenterPermGraph(final DirectedGraph graph) { int result = Integer.MAX_VALUE; for(DirectedGraph.Vertex center : graph.vertices) { int num = 2 * graph.vertices.length - 1 - graph.getOutcomingArcs(center).size() - graph.getIncomingArcs(center).size() + (graph.containsArc(center, center) ? 1 : 0); final int n = graph.vertices.length - 1; final List<Pair<Integer, Integer>> edges = CollectionFactory.createArrayList(); for(DirectedGraph.Arc arc : graph.arcs) { if(!center.equals(arc.from) && !(center.equals(arc.to))) { int i = arc.from.index; int j = arc.to.index; if(i > center.index) { --i; } if(j > center.index) { --j; } edges.add(new Pair(i, j)); } } final int matching = GraphUtils.calcNumMatchingBipartite(n, n, edges); num += edges.size() - matching; num += n - matching; result = Math.min(result, num); } return result; } public static class GraphUtils { public static int calcNumMatchingBipartite(final int n, final int m, final List<Pair<Integer, Integer>> edges) { final MatchingBipartiteSolver solver = new MatchingBipartiteSolver(n, m, edges); return solver.solve(); } private static class MatchingBipartiteSolver { private final int n; private final int m; private final List<Integer>[] edges; private final Integer[] match; private final boolean[] visited; public MatchingBipartiteSolver (final int n, final int m, final List<Pair<Integer, Integer>> edges) { this.n = n; this.m = m; this.edges = new List[n]; for(int i = 0; i < n; ++i) { this.edges[i] = CollectionFactory.createArrayList(); } for(final Pair<Integer, Integer> edge: edges) { this.edges[edge.first].add(edge.second); } match = new Integer[n + m]; visited = new boolean[n + m]; } public int solve() { int result = 0; for(;;) { Arrays.fill(visited, false); int gain = 0; for(int i = 0; i < n; ++i) { if(match[i] == null && !visited[i] && tryMatch(i)) { ++gain; } } if(gain > 0) { result += gain; } else { break; } } return result; } private boolean tryMatch(final int i) { visited[i] = true; for(int j : edges[i]) { if(!visited[j + n]) { visited[j + n] = true; final Integer k = match[j + n]; if(k == null || (!visited[k] && tryMatch(k))) { match[j + n] = i; match[i] = j + n; return true; } } } return false; } } } public static class DirectedGraph { public static class Vertex { public final int index; public Vertex(int index) { this.index = index; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vertex vertex = (Vertex) o; if (index != vertex.index) return false; return true; } @Override public int hashCode() { return index; } } public static class Arc { public final Vertex from; public final Vertex to; public Arc(Vertex from, Vertex to) { this.from = from; this.to = to; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Arc arc = (Arc) o; if (!from.equals(arc.from)) return false; if (!to.equals(arc.to)) return false; return true; } @Override public int hashCode() { int result = from.hashCode(); result = 31 * result + to.hashCode(); return result; } } final public Vertex[] vertices; final public Arc[] arcs; public DirectedGraph(final int n, final Pair<Integer, Integer>[] arcs) { vertices = new Vertex[n]; this.arcs = new Arc[arcs.length]; for(int i = 0; i < n; ++i) { vertices[i] = new Vertex(i); } for(int i = 0; i < arcs.length; ++i) { this.arcs[i] = new Arc(vertices[arcs[i].first], vertices[arcs[i].second]); } } public List<Arc> getOutcomingArcs(final Vertex v) { final List<Arc> result = CollectionFactory.createArrayList(); for(Arc arc : arcs) { if(arc.from.equals(v)) { result.add(arc); } } return result; } public List<Arc> getIncomingArcs(final Vertex v) { final List<Arc> result = CollectionFactory.createArrayList(); for(Arc arc : arcs) { if(arc.to.equals(v)) { result.add(arc); } } return result; } public boolean containsArc(final Vertex from, final Vertex to) { for(Arc arc : arcs) { if(arc.from.equals(from) && arc.to.equals(to)) { return true; } } return false; } } public static class MatrixIntMod { final int mod; final int[][] data; public MatrixIntMod(final int n, final int m, final int mod) { this.mod = mod; this.data = new int[n][m]; for(int i = 0; i < n; ++i) { Arrays.fill(data[i], 0); } } public MatrixIntMod(final int[][] data, final int mod) { this(data.length, data[0].length, mod); for(int i = 0; i < data.length; ++i) { for(int j = 0; j < data[i].length; ++j) { this.data[i][j] = ModNumberUtils.norm(mod, data[i][j]); } } } public MatrixIntMod(final int[] data, final int mod) { this(data.length, 1, mod); for(int i = 0; i < data.length; ++i) { this.data[i][0] = ModNumberUtils.norm(mod, data[i]); } } public int[] all() { int n = data.length; int m = data[0].length; final int[] res = new int[n * m]; int k = 0; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { res[k++] = data[i][j]; } } return res; } public MatrixIntMod mult(final MatrixIntMod val) { if(data[0].length != val.data.length) throw new RuntimeException("dimensions for mult are wrong"); final int n = data.length; final int m = data[0].length; final int l = val.data[0].length; final MatrixIntMod res = new MatrixIntMod(n, l, mod); for(int i = 0; i < n; ++i) { for(int j = 0; j < l; ++j) { for(int k = 0; k < m; ++k) { res.data[i][j] = ModNumberUtils.add(mod, res.data[i][j], ModNumberUtils.mult(mod, data[i][k], val.data[k][j])); } } } return res; } public int[] mult(final int[] ar) { return mult(new MatrixIntMod(ar, mod)).all(); } public MatrixIntMod power(final long t) { if(t == 0) return eye(data.length, mod); MatrixIntMod res = power(t >> 1); res = res.mult(res); if((t & 1) == 1) { res = res.mult(this); } return res; } public static MatrixIntMod eye(final int n, final int mod) { final MatrixIntMod res = new MatrixIntMod(n, n, mod); if(mod > 1) { for(int i = 0; i < n; ++i) { res.data[i][i] = 1; } } return res; } } public static class ModNumberUtils { public static int add(int mod, int a, int b) { a += b; if(a >= mod) { a -= mod; } return a; } public static int norm(int mod, int a) { a %= mod; if(a < 0) { a += mod; } return a; } public static int mult(int mod, int a, int b) { return (int)((long)a * b % mod); } } public static class Pair<X, Y>{ public X first; public Y second; public Pair(final X first, final Y second) { this.first = first; this.second = second; } } public static class NumberUtils { public static interface Factorizer { List<Integer> factorize(int number); } /** * thread safe Factorizer */ public static Factorizer createSmallNumberFactorizer(final int upperBound) { return new SmallNumberFactorizer(upperBound); } /** * thread safe */ private static class SmallNumberFactorizer implements Factorizer { private int[] divisors; private final int upperBound; private boolean prepared = false; /** * lazy * time complexity O(n * log(n) * log(log(n)) * memory complexity O(n) */ public SmallNumberFactorizer(final int upperBound) { this.upperBound = upperBound; } private synchronized void prepare() { divisors = new int[upperBound]; Arrays.fill(divisors, 0); for(int i = 2; i * i < upperBound; ++i) { if(divisors[i] == 0) { for(int j = i * i; j < upperBound; j += i) { if(divisors[j] == 0) { divisors[j] = i; } } } } prepared = true; } /** * complexity O(result) */ public List<Integer> factorize(int number) { synchronized (this) { if(!prepared) { prepare(); } } final List<Integer> result = CollectionFactory.createArrayList(); if(number < 2) return result; if(number >= upperBound) throw new RuntimeException("number should be less than upper bound"); while(divisors[number] > 0) { result.add(divisors[number]); number /= divisors[number]; } result.add(number); return result; } } } public static class CollectionFactory { public static<T> List<T> createArrayList() { return new ArrayList<>(); } public static<T> List<T> createArrayList(final int capacity) { return new ArrayList<>(capacity); } } public static class CollectionUtils { public static<T> List<T> unique(final List<T> list) { final List<T> result = CollectionFactory.createArrayList(); T p = null; for(T elem : list) { if(!elem.equals(p)) { result.add(elem); p = elem; } } return result; } public static<T extends Comparable<T>> T max(final List<T> list, final T lowerBound) { T result = lowerBound; for(T elem : list) { if(elem.compareTo(result) > 0) { result = elem; } } return result; } } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.sql.Time; import java.util.*; import java.math.BigInteger; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; public class Main{ void run(){ Locale.setDefault(Locale.US); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // boolean oj = true; try{ if( oj ){ sc = new FastScanner( new InputStreamReader(System.in ) ); out = new PrintWriter( new OutputStreamWriter(System.out) ); } else{ sc = new FastScanner(new FileReader("in.txt") ); // sc = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") ); out = new PrintWriter( new FileWriter("out.txt") ); } } catch (Exception e) { System.exit(-1); } long tB = System.currentTimeMillis(); solve(); if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 ); out.flush(); } class FastScanner{ BufferedReader br; StringTokenizer st = new StringTokenizer(""); FastScanner( InputStreamReader a ){ br = new BufferedReader(a); } FastScanner( FileReader a ){ br = new BufferedReader(a); } String next(){ while( !st.hasMoreTokens() ) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } return st.nextToken(); } String readLine(){ try { return br.readLine(); } catch (Exception e) { return null; } } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } } FastScanner sc; PrintWriter out; public static void main(String[] args){ new Main().run(); // new Thread( null, new Runnable() { // @Override // public void run() { // new Main().run(); // } // }, "LOL", 256L * 1024 * 1024 / 2 ).run(); // }, "LOL", 2000 * 1024 * 1024 ).run(); } void TLE(){ for(;;); } void MLE(){ int[][] adj = new int[1024*1024][]; for( int i = 0; i < adj.length; ++i ) adj[i] = new int[1024*1024]; } void exit( int val ){ out.flush(); System.exit(val); } ////////////////////////////////////////////////////////////////////////////////////////// int n, m; boolean[][] grid; ArrayList<Integer>[] gr; int c; int[] mt; boolean[] u; boolean try_kuhn( int v ){ if( u[v] ) return false; u[v] = true; for( int to : gr[v] ){ if( to == c ) continue; if( mt[to]==-1 || try_kuhn(mt[to]) ){ mt[to] = v; return true; } } return false; } void solve(){ n = sc.nextInt(); m = sc.nextInt(); grid = new boolean[n+1][n+1]; gr = new ArrayList[n+1]; for( int v = 1; v <= n; ++v ) gr[v] = new ArrayList<Integer>(); for( int it = 0; it < m; ++it ){ int a = sc.nextInt(); int b = sc.nextInt(); grid[a][b] = true; gr[a].add(b); } int ans = Integer.MAX_VALUE; for( c = 1; c <= n; ++c ){ int curAns = 0; for( int v = 1; v <= n; ++v ) if( v != c ){ if( !grid[c][v] ) ++curAns; if( !grid[v][c] ) ++curAns; } if( !grid[c][c] ) ++curAns; mt = new int[n+1]; fill( mt, -1 ); for( int i = 1; i <= n; ++i ) if( i != c ){ u = new boolean[n+1]; try_kuhn(i); } int szMt = 0; for( int i = 1; i <= n; ++i ) if( mt[i] != -1 ) ++szMt; curAns += n - 1 - szMt; for( int a = 1; a <= n; ++a ){ for( int b : gr[a] ){ if( a==c || b==c ) continue; if( a!=mt[b] ) ++curAns; } } // out.printf( "%d %d\n", c, curAns ); ans = min( ans, curAns ); } out.println( ans ); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author sheep */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); boolean[][] map = new boolean[n][n]; int m = in.nextInt(); int[] us = new int[m]; int[] vs = new int[m]; for (int i = 0; i < m; ++i) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; map[u][v] = true; us[i] = u; vs[i] = v; } int ans = Integer.MAX_VALUE; for (int center = 0; center < n; ++center) { int fixed = 0; for (int i = 0; i < n; ++i) { if (!map[center][i]) { ++fixed; } if (!map[i][center] && i != center) { ++fixed; } } MaxFlow flow = new MaxFlow(n * 2 + 2, n * 2, n * 2 + 1); for (int i = 0; i < n; ++i) { if (i == center) continue; flow.insert(n * 2, i, 1); flow.insert(i + n, n * 2 + 1, 1); } for (int i = 0; i < m; ++i) { if (us[i] == center || vs[i] == center) { continue; } flow.insert(us[i], vs[i] + n, 1); ++fixed; } ans = Math.min(ans, fixed + (n - 1) - 2 * flow.maxFlow()); } out.println(ans); } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new UnknownError(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class MaxFlow { public class Edge { public int u,v,c; public Edge next,r; public Edge(int u,int v,int c) { this.u = u; this.v = v; this.c = c; next = r = null; } } public Edge vertex[]; public int height[], nheight[]; public int s, t, n; public void init(int n,int s,int t) { height = new int[n+1]; nheight = new int[n+1]; vertex = new Edge[n+1]; this.s = s; this.t = t; this.n = n; } public MaxFlow(int n,int s,int t) { init(n,s,t); } public void insert(int u,int v,int c) { Edge e = new Edge(u,v,c); Edge r = new Edge(v,u,0); e.r = r; r.r = e; e.next = vertex[u]; vertex[u] = e; r.next = vertex[v]; vertex[v] = r; } public int augPath(int u,int push) { if (u == t) return push; int flow = push, minheight = n-1; for (Edge e = vertex[u]; e != null; e = e.next) if (e.c != 0) { if (height[e.v] + 1 == height[e.u]) { int delta = flow < e.c ? flow : e.c; if (delta > 0) delta = augPath(e.v,delta); e.c -= delta; e.r.c += delta; flow -= delta; if (0 == flow || height[s] >= n) return push - flow; } minheight = Math.min(minheight, height[e.v]); } if (push == flow) { --nheight[height[u]]; if (0 == nheight[height[u]]) height[s] = n; height[u] = ++minheight; ++nheight[height[u]]; } return push - flow; } public int maxFlow() { Arrays.fill(height, 0); Arrays.fill(nheight, 0); nheight[0] = n; int flow = 0; while (height[s] < n) flow += augPath(s,Integer.MAX_VALUE); return flow; } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import com.sun.java_cup.internal.runtime.virtual_parse_stack; import java.util.Arrays; import java.util.Scanner; /** * Created by ali on 2/3/14. */ public class D { public static void main(String [] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean [][] graph = new boolean[n][n]; for(int i = 0 ; i < m ; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; graph[a][b] = true; } int res = Integer.MAX_VALUE; for(int center = 0 ; center < n ; center++) { int calc = 0; for(int i = 0 ; i < n ; i++) { if(!graph[center][i]) calc++; if(!graph[i][center]) calc++; } if(!graph[center][center]) calc--; int [] match = new int[n]; Arrays.fill(match, -1); int max = 0; for(int i = 0 ; i < n ; i++) if(i != center) if(can(i, graph, new boolean[n], center, match)) max++; int unusable = m - (2*n - 1 - calc) - max; calc += unusable; calc += (2*(n-1) - 2*max)/2; res = Math.min(res, calc); } System.out.println(res); } private static boolean can(int at, boolean[][] graph, boolean[] visited, int center, int [] match) { if(visited[at]) return false; visited[at] = true; for(int to = 0 ; to < graph.length ; to++) if(graph[at][to]) if(to != center) if(match[to] == -1 || can(match[to], graph, visited, center, match)) { match[to] = at; return true; } return false; } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { ArrayList<Integer>[] g; int n, m; boolean[][] have; int[] x; int[] y; boolean[] used; int stop; public void solve(int testNumber, FastScanner in, PrintWriter out) { n = in.nextInt(); g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); have = new boolean[n][n]; m = in.nextInt(); for (int i = 0; i < m; i++) { int a = in.nextInt(); int b = in.nextInt(); --a; --b; g[a].add(b); have[a][b] = true; } int res = Integer.MAX_VALUE; for (int center = 0; center < n; center++) res = Math.min(res, solve(center)); out.print(res); } int solve(int v) { stop = v; int withV = 0; int add = 0; for (int i = 0; i < n; i++) if (i != v) if (have[v][i]) withV++; else add++; for (int i = 0; i < n; i++) if (i != v) if (have[i][v]) withV++; else add++; if (have[v][v]) withV++; else add++; x = new int[n]; y = new int[n]; used = new boolean[n]; Arrays.fill(x, -1); Arrays.fill(y, -1); int matched = 0; for (int i = 0; i < n; i++) if (i != v && x[i] == -1) { Arrays.fill(used, false); if (dfs(i)) matched++; } add += n - 1 - matched; add += m - withV - matched; return add; } boolean dfs(int v) { if (used[v]) return false; used[v] = true; for (int to : g[v]) if (to != stop && y[to] == -1) { x[v] = to; y[to] = v; return true; } for (int to : g[v]) if (to != stop && dfs(y[to])) { x[v] = to; y[to] = v; return true; } return false; } } class FastScanner { BufferedReader reader; StringTokenizer tokenizer; public FastScanner(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line; try { line = reader.readLine(); } catch (IOException e) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } }
cubic
387_D. George and Interesting Graph
CODEFORCES
import java.util.Scanner; public class P23A { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String input = scan.nextLine(); System.out.println(F(input)); } static int F(String string){ int ans =0; for (int i = 0; i < string.length(); i++) { for (int j = 1; j < string.length()-i; j++) { String s = string.substring(i, i+j); int a=string.indexOf(s); int b=string.lastIndexOf(s); if ( a >= 0 && b >=0 && a !=b) ans =Math.max(ans, s.length()); } } return ans; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class A { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s = sc.next(); for (int l = s.length(); l > 0; --l) { HashSet<String> set = new HashSet<String>(); for (int i = 0; i < s.length() - l + 1; ++i) if (set.contains(s.substring(i, i + l))) { System.out.println(l); return; } else { set.add(s.substring(i, i + l)); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class Prob023A { public static void main( String[] Args ) { Scanner scan = new Scanner( System.in ); String s = scan.next(); all: for ( int x = s.length() - 1; x >= 0; x-- ) for ( int y = 0; x + y <= s.length(); y++ ) { String sub = s.substring( y, y + x ); if ( s.indexOf( sub, y + 1 ) >= 0 ) { System.out.println( x ); break all; } } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class A23 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); Map<String, Boolean> map = new HashMap<String, Boolean>(); for (int i = s.length(); i >= 1; i--) { map.clear(); for (int j = 0; j < s.length()-i+1; j++) { String temp = s.substring(j, j+i); if (map.containsKey(temp)) { System.out.println(i); return; } map.put(temp, true); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
/** * MxNINJA 04:06:52 ص 14/01/2014 */ import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder line = new StringBuilder(reader.readLine()); int length = 0; for (int head = 0; head < line.length(); head++) { for (int tail = line.length() - 1; tail > head; tail--) { String subString = line.substring(head, tail); if(line.indexOf(subString,head+1)>-1){ length = Math.max(subString.length(), length); } } } System.out.println(length); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class YouAreGivenAString { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String s=r.readLine(); int max=0; for(int i=1;i<s.length();i++){ for (int j = 0; j <= s.length()-i; j++) { String sub=s.substring(j,j+i); if(count(s,sub)>=2) max=Math.max(max, i); } } System.out.println(max); } private static int count(String s, String sub) { int l=sub.length(); int c=0; for(int i=0;i<=s.length()-l;i++){ if(s.substring(i,i+l).equals(sub)) c++; } return c; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); String a = r.next(); char[] c = a.toCharArray(); for(int l = a.length()-1; l >= 1; l--){ for(int i = 0; i <= a.length()-l; i++){ int j = i+l-1; for(int s = 0; s <= a.length()-l; s++){ if(i == s)continue; if(a.substring(i, i+l).equals(a.subSequence(s, s+l))){ System.out.println(l); System.exit(0); } } } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main( String[] args ){ Scanner cin = new Scanner( System.in ); String s = cin.next(); int n = s.length(); char[] ss = new char[ n ]; ss = s.toCharArray(); int ans = 0; for (int i=0; i<n; i++) for (int j=i+1; j<n; j++){ int k = 0; while ( i+k<n && j+k<n && ss[i+k] == ss[j+k] ) k++; ans = Math.max( ans, k ); } System.out.println( ans ); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class prob1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.next(); int n = s.length(); int i = n-1; CharSequence temp; for(i = n-1; i > 0; i--) for(int j = 0 ; j <= n-i; j++) { temp = s.subSequence(j, i+j); if( s.substring(j+1, n).contains(temp) || s.substring(0, j+i-1).contains(temp)) { System.out.println(i); return; } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; 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(""); void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); String s = in.readLine(); for (int len = s.length() - 1; len > 0; len--) { Set<String> set = new HashSet<String>(); for (int i = 0; i + len <= s.length(); i++) { String ss = s.substring(i, i + len); if (set.contains(ss)) { out.println(len); out.close(); return; } set.add(ss); } } out.println(0); out.close(); } 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; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class a { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int len = s.length(); for(int i=len-1; i>=1; --i) { for(int j=0; j<=len - i; ++j) { String ss = s.substring(j, j+i); if(s.substring(j+1).indexOf(ss)!=-1) { System.out.println(ss.length()); return; } } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class Main implements Runnable { public void _main() throws IOException { String s = next(); for (int len = s.length(); len >= 1; len--) { for (int i = 0; i + len <= s.length(); i++) for (int j = i + 1; j + len <= s.length(); j++) if (s.substring(i, i + len).equals(s.substring(j, j + len))) { out.print(len); return; } } out.print(0); } private BufferedReader in; private PrintWriter out; private StringTokenizer st; private String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String rl = in.readLine(); if (rl == null) return null; st = new StringTokenizer(rl); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { new Thread(new Main()).start(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); _main(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(202); } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class Main implements Runnable { Scanner in; PrintWriter out; //= new PrintWriter(System.out); public static void main(String[] args) throws FileNotFoundException, IOException { new Thread(new Main()).start(); } public class Pair { public long last; public long count; public int L; Pair(long l, long c) {last = l; count = c;} Pair(long l, long c, int L) {last = l; count = c; this.L = L;} } public void run() { final String name = "B-small"; //try { in = new Scanner(System.in);// (new File(name + ".in"));//StreamTokenizer(new FileReader(new File(name + ".in"))); out = new PrintWriter(System.out); // new PrintWriter(new File(name + ".out")); //= new PrintWriter(System.out); //} catch (IOException e) {} String s = in.next().trim(); int n = s.length(); boolean[][] a = new boolean[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) a[i][j] = (s.charAt(i) == s.charAt(j)); int max = 0; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { int k =0; while (i + k < n && j + k < n && a[i + k][j + k]) ++k; if (max < k) max = k; } out.println(max); out.flush(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; public class A { private BufferedReader in; private StringTokenizer st; private PrintWriter out; private void solve() throws IOException { String s = next(); for (int length = s.length() - 1; length > 0; --length) { Set<String> h = new HashSet<String>(); int count = 0; for (int i = 0; i + length <= s.length(); ++i) { h.add(s.substring(i, i + length)); ++count; } if (count != h.size()) { out.println(length); return; } } out.println(0); } public void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); out.close(); in.close(); } private void eat(String s) { st = new StringTokenizer(s); } private String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } private BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new A().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class A0023 { public static void main(String args[]) throws Exception { new A0023(); } A0023() throws Exception { PandaScanner sc = null; PrintWriter out = null; try { sc = new PandaScanner(System.in); out = new PrintWriter(System.out); } catch (Exception ignored) { } String s = sc.next(); int i = s.length() - 1; Test: for (; i > 0; i--) { HashSet<String> set = new HashSet<String>(); for (int j = 0; j + i <= s.length(); j++) { String ss = s.substring(j, j + i); if (set.contains(ss)) { break Test; } set.add(ss); } } out.println(i); out.close(); System.exit(0); } //The PandaScanner class, for Panda fast scanning! public class PandaScanner { BufferedReader br; StringTokenizer st; InputStream in; PandaScanner(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String next() throws Exception { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return next(); } return st.nextToken(); } public boolean hasNext() throws Exception { return (st != null && st.hasMoreTokens()) || in.available() > 0; } public long nextLong() throws Exception { return Long.parseLong(next()); } public int nextInt() throws Exception { return Integer.parseInt(next()); } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class ProblemA { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String line = s.readLine(); int len = line.length(); int max = 0; for (int i = 0 ; i < len ; i++) { for (int j = i+1 ; j <= len ; j++) { String sch = line.substring(i, j); for (int k = i+1 ; k + (j - i) <= len ; k++) { String tch = line.substring(k, k+(j-i)); if (sch.equals(tch)) { max = Math.max(max, (j-i)); } } } } out.println(max); out.flush(); } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; public class A23 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); for(int length = s.length(); length > 0; length--) { for(int start = 0; start + length <= s.length(); start++) { String test = s.substring(start, start+length); if(s.indexOf(test) != s.lastIndexOf(test)) { System.out.println(length); return; } } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
//package arbuz; import java.util.Scanner; public class Arbuz { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int i, j, current, longest = 0; for (i = 0; i < s.length(); i++) { for (j = 0; j < s.length(); j++) { if (i != j) { int ti = i, tj = j; current = 0; while (ti < s.length() && tj < s.length() && s.charAt(ti) == s.charAt(tj)) { current++; ti++; tj++; } if (current > longest) { longest = current; } } } } System.out.println(longest); } }
cubic
23_A. You're Given a String...
CODEFORCES
// by agus.mw import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws Exception { new Main().doWork(); } void doWork() throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); String text = reader.readLine().trim(); int out = 0; for(int i=0;i<text.length();i++){ for(int j=i+1;j<text.length();j++){ for(int len = out+1;len+j<=text.length();len++){ if(text.substring(i,i+len).compareTo(text.substring(j,j+len))==0){ out = len; } } } } String buf = ""+out; writer.write(buf,0,buf.length()); writer.newLine(); writer.flush(); writer.close(); reader.close(); } String process(){ return "1"; } int[] toIntArray(String line){ String[] p = line.split("[ ]+"); int[] out = new int[p.length]; for(int i=0;i<p.length;i++) out[i] = Integer.valueOf(p[i]); return out; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author madi */ public class GivenString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); String sub = ""; int count = 0; int max = 0; for (int i = 0; i < line.length() - 1; i++) { sub = line.substring(i, i + 1); int q = i + 1; int p; int r = i; while (q < line.length() && q > 0) { p = q; r = i; int ind = line.indexOf(sub, p); count = 0; if (ind != -1) { for (int j = ind; j < line.length(); j++) { if (line.substring(j, j + 1).equalsIgnoreCase(line.substring(r, r + 1))) { r++; count++; } else { break; } } if (count > max) { max = count; } } q = ind + 1; } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class Main { static Scanner cin = new Scanner(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter cout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String[] agrs) throws IOException{ String line = cin.nextLine(); HashMap<String, Integer> map = new HashMap<String, Integer>(); int ans = 0; for (int i = 0; i < line.length(); ++i) { StringBuffer str = new StringBuffer(""); for (int j = i; j < line.length(); ++j) { str.append(line.charAt(j)); if (!map.containsKey(str.toString())) { //cout.println(str.toString()); map.put(str.toString(), 1); } else { ans = str.length() > ans ? str.length() : ans; } } } cout.println(ans); cin.close(); cout.close(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; /** * @author Alexander Grigoryev * Created on 01.08.11 */ public class Main { static Scanner in = new Scanner(System.in); public static void main(String[] args) { String s = in.nextLine(); int k, ans = 0; for(int i = 0; i < s.length(); i++) for(int j = i + 1; j < s.length(); j++) { for(k = 0; j + k < s.length(); k++) { if(s.charAt(i + k) != s.charAt(j + k)) break; } if(ans < k) ans = k; } System.out.println(ans); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(),c; int n = s.length(),a,b; for(int sz = n ; sz >= 1 ; sz--) { for(int i = 0 ; i+sz <= n ; i++) { c = s.substring(i, i+sz); a = s.indexOf(c,0); if(a < 0) continue; b = s.indexOf(c,a+1); if(b < 0) continue; System.out.println(sz); return; } // for j } // for i System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class St { static void metod() throws Exception { Scanner in = new Scanner(System.in); String str = in.next(); int max = 0; for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length() + 1; j++) { for (int k = 0; k < str.length(); k++) { for (int n = k + 1; n < str.length() + 1; n++) { if ((str.substring(i, j).equals(str.substring(k, n))) && (k != i)) { if (j - i > max) max = j - i; } } } } } System.out.println(max); } public static void main(String args[]) throws Exception { St.metod(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class test { static boolean isOK(String str, int len) { HashSet<String> hs=new HashSet<String>(); for(int i=0;i<=str.length()-len;i++) { String s=str.substring(i,len+i); if(hs.contains(s)) return true; else hs.add(s); } return false; } public static void main(String[] args) { Scanner in=new Scanner(System.in); String str=in.next(); int i; for(i=str.length()-1;i>=1;i--) if(isOK(str,i)) { break; } System.out.println(i); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class givenstring { public static void main(String[] args){ Scanner reader = new Scanner(System.in); String in = reader.next(); int max = 0; for(int i = 0; i < in.length(); i++){ for(int j = i+1; j < in.length(); j++){ //take this substring String consider = in.substring(i, j); for(int k = i+1; k < in.length(); k++){ if(k + consider.length() > in.length()) break; else if(in.substring(k, k+consider.length()).equals(consider)) max = Math.max(max, consider.length()); } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; public class A { Scanner sc = new Scanner(System.in); void run(){ String s = sc.next(); String subS; int max = 0; for (int i=0;i<s.length();i++) { for (int j=i+1;j<s.length()+1;j++) { subS = s.substring(i, j); for (int k=i+1;k<s.length();k++) { if ( s.startsWith(subS,k) ){ if ( max < subS.length() ) max = subS.length(); } } } } System.out.println(max); return; } public static void main(String[] args){ new A().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class DoubleWord implements Runnable { boolean isLocalMode =false; private void doJob() throws Exception { //do here String s = nextToken(); int max=0; for(int i = 0;i<s.length();i++){ for(int j=i+1;j<s.length()+1;j++){ String s1 = s.substring(i, j); if(s.substring(i+1).contains(s1)){ max = Math.max(max,s1.length()); } } } writer.write(""+max); } public static void main(String[] args) { new DoubleWord().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(getReader()); tokenizer = null; writer = new PrintWriter(System.out); //do job doJob(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } 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 nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public Reader getReader() throws FileNotFoundException { if (isLocalMode) { return new FileReader("input.txt"); } else { return new InputStreamReader(System.in); } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; import static java.util.Arrays.*; import static java.lang.Math.*; import java.math.*; public class Main { void run() throws IOException { String s = token(); HashSet <String> h; int n = s.length(); int r = 0; loop: for (int i = 1; i <= n; i++) { h = new HashSet(); for (int j = 0; j < n - i + 1; j++) { String t = s.substring(j, j + i); if (h.contains(t)) { r = i; continue loop; } else { h.add(t); } } } System.out.println(r); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); //final String FILENAME = "dvd"; //in = new BufferedReader(new FileReader(new File(FILENAME + ".in"))); //out = new PrintWriter(new File(FILENAME + ".out")); in = new BufferedReader(new InputStreamReader(System.in)); //in = new Scanner(System.in); out = new PrintWriter(System.out); st = new StringTokenizer(" "); new Main().run(); out.close(); } static BufferedReader in; //static Scanner in; static PrintWriter out; static StringTokenizer st; String token() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nint() throws IOException { return Integer.parseInt(token()); } long nlong() throws IOException { return Long.parseLong(token()); } double ndouble() throws IOException { return Double.parseDouble(token()); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A implements Runnable { private void solve() throws IOException { String str = nextToken(); for (int i=str.length()-1; i>=0; --i) for (int j=0; j+i<=str.length(); ++j) if (str.substring(j+1).contains(str.substring(j, j+i))) { writer.println(i); return; } writer.println(0); } public static void main(String[] args) { new Thread(new A()).start(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } 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 nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class Main { /** * @author hunglee */ public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); in.nextToken(); String s = in.sval; int l = s.length(); int n = l - 1; String st, sub; while (n > 0) { for (int i = 0; i < l - n; ++i) { st = s.substring(i, n + i); sub = s.substring(i + 1); if (sub.indexOf(st) != -1) { System.out.println(n); System.exit(0); } } n--; } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class OverlapedString { public static void main(String args[]) throws Exception { OverlapedString os = new OverlapedString(); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = stdin.readLine()) != null) { System.out.println(os.handleOverlap(line)); } } private int handleOverlap(String str) { int len = str.length(); int count = 0; for(int i=0;i<len;i++) for(int j=i+1;j<len;j++) { String _tmp = str.substring(i,j); if(_tmp!=null&&_tmp.length()>0) { if(getOverlapCount(str,_tmp)>1) { if(_tmp.length()>count) count = _tmp.length(); } } } return count; } private int getOverlapCount(String str,String sub) { int start = 0; int count = 0; while(start<str.length()) { start = str.indexOf(sub,start); if(start==-1) break; else { start++; count++; } } return count; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class A { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; A a = new A(filePath); } public A(String inputFile) { openInput(inputFile); readNextLine(); String s=line; int ret=0; for(int i=0; i<s.length(); i++) { for(int j=i+1; j<s.length()+1; j++) { String a=s.substring(i, j); if(s.indexOf(a, i+1)>-1)ret=Math.max(ret, a.length()); } } System.out.println(ret); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class A { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); String s = sc.next(); int n = s.length(); for (int i = n; i >= 1; i--) { Set<String> set = new HashSet<String>(); for (int j = 0; j < n-i+1; j++) { String t = s.substring(j, j+i); if (set.contains(t)) { System.out.println(i); return; } set.add(t); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class A { public static void main(String[] args) { new A(new Scanner(System.in)); } public A(Scanner in) { TreeSet<String> ts = new TreeSet<String>(); ArrayList<String> sr = new ArrayList<String>(); String s = in.next(); for (int i=0; i<s.length(); i++) { for (int j=i+1; j<=s.length(); j++) { String ss = s.substring(i, j); if (ts.contains(ss)) { sr.add(ss); } ts.add(ss); } } int res = 0; for (String ss : sr) { if (ss.length() > res) res = ss.length(); } System.out.printf("%d%n", res); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class A { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s = sc.next(); for (int l = s.length(); l > 0; --l) { HashSet<String> set = new HashSet<String>(); for (int i = 0; i < s.length() - l + 1; ++i) if (set.contains(s.substring(i, i + l))) { System.out.println(l); return; } else { set.add(s.substring(i, i + l)); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class YouAreGivenAString { void run() { try { BufferedReader bfd = new BufferedReader(new InputStreamReader( System.in)); int i, j, k, mxLen = 0; String s= bfd.readLine(); for(i=0; i<s.length(); ++i){ for(j=i+1; j<s.length()+1; ++j){ String s2 = s.substring(i, j); if(s2.length()<=mxLen) continue; int cnt=0; for(k=0; k<s.length(); ++k){ if(s.length()>=k+s2.length()) if(s2.equals(s.substring(k,k+s2.length()))){ cnt++; if(cnt>1)mxLen = Math.max(mxLen, s2.length()); } } } } System.out.println(mxLen); } catch (Exception e) { } } public static void main(String[] args) { new YouAreGivenAString().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class Word { static String word; private static void check(String subword) { int i = 0; int j = 0; while (j + subword.length() <= word.length()) { if (word.substring(j).startsWith(subword)){ i++; } j++; } if (i > 1){ System.out.println(subword.length()); System.exit(0); } } public static void main(String[] arg) { Scanner in = new Scanner(System.in); word = in.next(); if (word.length() == 1) { System.out.println(0); return; } for (int i = word.length() - 1; i > 0; i--) { int j = 0; while (j + i <= word.length()) { check(word.substring(j, i+j)); j++; } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class YoureGivenAString { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); String str = f.readLine(); int max = 0; for (int i = 0; i < str.length(); i++) for (int j = i+1; j <= str.length(); j++) { String s = str.substring(i,j); if (str.indexOf(s) >= 0 && str.substring(str.indexOf(s)+1).indexOf(s) >= 0) max = Math.max(max, j-i); } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; /** * User: alms * Date: 09.07.2010 * Time: 18:57:44 */ public class Solution { public static void main(String[] args) throws Exception { final String str; final BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); str = r.readLine(); int max = 0; for (int x = 0; x < str.length(); x++) { for (int y = x + 1; y < str.length(); y++) { int c = 0; for (;c + x < str.length() && y + c < str.length(); c++) { if (str.charAt(x + c) != str.charAt(y + c)) { break; } } if (c > max) { max = c; } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import java.util.TreeSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Trung Pham */ public class A { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); String val = in.next(); ArrayList<String> list = new ArrayList(); for(int i = 0; i < val.length() ; i++){ list.add(val.substring(i)); } Collections.sort(list); int result = 0; for(int i = 1; i < list.size() ; i++){ String other = list.get(i - 1); int temp = 0; for(int j = 0; j < list.get(i).length() && j < other.length() ; j++){ if(other.charAt(j) == list.get(i).charAt(j)){ temp++; }else{ break; } } if(temp > result){ result = temp; } } out.println(result); out.close(); } public static int dist(int x0, int y0, int x1, int y1) { return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1); } public static boolean isRight(int a, int b, int c) { if (a == 0 || b == 0 || c == 0) { return false; } if (a == b + c) { return true; } if (b == a + c) { return true; } if (c == a + b) { return true; } return false; } public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } static int pow(int a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } int val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } static Point add(Point a, Point b) { return new Point(a.x + b.x, a.y + b.y); } static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point: " + x + " " + y; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); // br = new BufferedReader(new FileReader("input.txt")); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Task { private static final boolean readFromFile = false; public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FileOutputStream fileOutputStream; FileInputStream fileInputStream; if (readFromFile){ try{ fileInputStream = new FileInputStream(new File("input.txt")); fileOutputStream = new FileOutputStream(new File("output.txt")); }catch (FileNotFoundException e){ throw new RuntimeException(e); } } PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream); InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream); Solver s = new Solver(in,out); s.solve(); out.close(); } } class Solver{ InputReader in; PrintWriter out; public void solve(){ String s = in.nextLine(); for (int len=s.length()-1;len>=1;len--) for (int i=0;i<s.length()-len+1;i++) for (int j=i+1;j<s.length()-len+1;j++) if (s.substring(i,i+len).equals(s.substring(j,j+len))){ out.println(len); return; } out.println(0); } Solver(InputReader in, PrintWriter out){ this.in=in; this.out=out; } } class InputReader{ private BufferedReader buf; private StringTokenizer tok; InputReader(InputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } InputReader(FileInputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } public String next(){ while (tok==null || !tok.hasMoreTokens()){ try{ tok = new StringTokenizer(buf.readLine()); }catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } 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()); } public String nextLine(){ try{ return buf.readLine(); }catch (IOException e){ return null; } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class Main { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder out = new StringBuilder(); public static void main(String[] args){ solve(); return; } // the followings are methods to take care of inputs. static int nextInt(){ return Integer.parseInt(nextLine()); } static long nextLong(){ return Long.parseLong(nextLine()); } static int[] nextIntArray(){ String[] inp = nextLine().split("\\s+"); int[] ary = new int[inp.length]; for (int i = 0; i < ary.length; i++){ ary[i] = Integer.parseInt(inp[i]); } return ary; } static int[] nextIntArrayFrom1(){ String[] inp = nextLine().split("\\s+"); int[] ary = new int[inp.length + 1]; for (int i = 0; i < inp.length; i++){ ary[i+1] = Integer.parseInt(inp[i]); } return ary; } static long[] nextLongArray(){ String[] inp = nextLine().split("\\s+"); long[] ary = new long[inp.length]; for (int i = 0; i < inp.length; i++){ ary[i] = Long.parseLong(inp[i]); } return ary; } static long[] nextLongArrayFrom1(){ String[] inp = nextLine().split("\\s+"); long[] ary = new long[inp.length + 1]; for (int i = 0; i < inp.length; i++){ ary[i+1] = Long.parseLong(inp[i]); } return ary; } static String nextLine(){ try { return reader.readLine().trim(); } catch (Exception e){} return null; } static void solve(){ String str = nextLine(); int max=0; int index=0; for(int i=0;i<str.length();i++){ for(int j=i+1;j<str.length();j++){ if(str.charAt(i)==str.charAt(j)){ int count=1; while(true){ if(str.length()<=i+count || str.length()<=j+count || str.charAt(i+count)!=str.charAt(j+count) ) break; count++; } if(max<count){ max=count; index=i; } } } } System.out.println(max); return; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class A { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s = sc.next(); for (int l = s.length(); l > 0; --l) { HashSet<String> set = new HashSet<String>(); for (int i = 0; i < s.length() - l + 1; ++i) if (set.contains(s.substring(i, i + l))) { System.out.println(l); return; } else { set.add(s.substring(i, i + l)); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.StringTokenizer; import java.util.AbstractCollection; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Zyflair Griffane */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; PandaScanner in = new PandaScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); A solver = new A(); solver.solve(1, in, out); out.close(); } } class A { public void solve(int testNumber, PandaScanner in, PrintWriter out) { String s = in.next(); String[] ss = Substring.allSubstrings(s); int res = 0; for (String sss: ss) { if (sss.length() <= res) continue; if (Substring.occurences(s, sss).length > 1) { res = sss.length(); } } out.println(res); } } class PandaScanner { public BufferedReader br; public StringTokenizer st; public InputStream in; public PandaScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } public String next() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine().trim()); return next(); } return st.nextToken(); } } class Substring { public static String[] allSubstrings(String s) { TreeSet<String> substrings = new TreeSet<String>(); int n = s.length(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { substrings.add(s.substring(i, j)); } } return substrings.toArray(new String[0]); } public static int[] occurences(String s, String target) { int n = s.length(); ArrayList<Integer> res = new ArrayList<Integer>(); int idx = s.indexOf(target); while (idx != -1) { res.add(idx); if (idx == n - 1) break; idx = s.indexOf(target, idx + 1); } n = res.size(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = res.get(i); } return arr; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class A { private static StreamTokenizer in; private static PrintWriter out; private static int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { in = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); out = new PrintWriter(System.out); String s = nextString(); int max = 0; for (int i=0; i<s.length(); i++) { for (int j=i+1; j<=s.length(); j++) { // System.out.println(i+ " "+ j); String u = s.substring(i,j); if (s.substring(i+1).indexOf(u) >= 0) { max = Math.max(max, u.length()); } } } out.println(max); out.flush(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class P1 { public static void main(String[] args) { String s = null; // citire try { // Scanner sc = new Scanner(new File("in.txt")); Scanner sc = new Scanner(System.in); s = sc.next(); } catch (Exception e) { e.printStackTrace(); } int n = s.length(); HashSet<String> h = new HashSet<String>(); String t=null; boolean b; int lmax = 0; for (int i=0; i<n; i++) { for (int j=i+1; j<=n; j++) { t = s.substring(i, j); b = h.add(t); // System.out.println(t + " " + b); if (b==false) { if (j-i>lmax) { lmax = j-i; // System.out.println(t); } } } } System.out.println(lmax); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String ...args) throws Throwable { Scanner in = new Scanner(System.in); String init = in.nextLine(); HashSet<String> h = new HashSet<String>(); for (int len = init.length() - 1; len >= 1; --len) { h.clear(); for (int pos = 0; pos + len <= init.length(); ++pos) { String now = init.substring(pos, pos + len); if (h.contains(now)) { System.out.println(len); return; } h.add(now); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; /************************************************************************* * Compilation: javac LRS.java * Execution: java LRS < file.txt * Dependencies: StdIn.java * * Reads a text corpus from stdin, replaces all consecutive blocks of * whitespace with a single space, and then computes the longest * repeated substring in that corpus. Suffix sorts the corpus using * the system sort, then finds the longest repeated substring among * consecutive suffixes in the sorted order. * * % java LRS < mobydick.txt * ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th' * * % java LRS * aaaaaaaaa * 'aaaaaaaa' * * % java LRS * abcdefg * '' * *************************************************************************/ import java.util.Arrays; public class LRS { // return the longest common prefix of s and t public static String lcp(String s, String t) { int n = Math.min(s.length(), t.length()); for (int i = 0; i < n; i++) { if (s.charAt(i) != t.charAt(i)) return s.substring(0, i); } return s.substring(0, n); } // return the longest repeated string in s public static String lrs(String s) { // form the N suffixes int N = s.length(); String[] suffixes = new String[N]; for (int i = 0; i < N; i++) { suffixes[i] = s.substring(i, N); } // sort them Arrays.sort(suffixes); // find longest repeated substring by comparing adjacent sorted suffixes String lrs = ""; for (int i = 0; i < N - 1; i++) { String x = lcp(suffixes[i], suffixes[i+1]); if (x.length() > lrs.length()) lrs = x; } return lrs; } // read in text, replacing all consecutive whitespace with a single space // then compute longest repeated substring public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); s = s.replaceAll("\\s+", " "); System.out.println(lrs(s).length()); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.util.StringTokenizer; import java.io.InputStreamReader; public class Main{ public static void main(String[] args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); int max=0; for(int i=0;i<s.length();i++){ int len=0; int k=i; boolean flag=false; for(int j=i+1;j<s.length();j++){ if(s.charAt(k)==s.charAt(j)){ len++; k++; flag=true; } else if(flag==true){ j=j-len; k=i; if(max<len) max=len; len=0; flag=false; } } if(max<len) max=len; } System.out.print(max); }}
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class substring { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.nextLine(); Boolean found = false; int i = s.length(); while(found==false) { i--; ArrayList<String> sub = new ArrayList<String>(); for(int j = 0; j <= s.length() - i; j++) { if(sub.contains(s.substring(j, j+i))) found = true; else sub.add(s.substring(j, j+i)); } } System.out.println(i); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Main20 { static ArrayList<Integer> primes = new ArrayList<Integer>(); static boolean[] prime = new boolean[1001]; public static void gen(){ Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i < 1001; i++) { if (prime[i]){ primes.add(i); for (int j = i*2; j < 1001; j+=i) prime[j] = false; } } } public static boolean isVowel(char c){ Character r = Character.toLowerCase(c); return (r == 'e' || r == 'a' || r == 'i' || r == 'o' || r == 'u'|| r == 'y'); } public static void main(String[] args) throws IOException { Scanner s = new Scanner(new InputStreamReader(System.in)); String str = s.next(); int x; int max= 0; for (int i = 0; i < str.length()-1; i++) { for (int j = i+1; j < str.length(); j++) { x = str.indexOf(str.substring(i,j),i+1) ; if (x != -1){ if (j-i > max) max = j-i; } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package substring; import java.util.*; /** * * @author lav */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scr = new Scanner(System.in); // System.out.println("entet strig"); String str = scr.nextLine(); int len =0; // System.out.println(str.substring(0, str.length())); for(int i=0;i<(str.length()-1);i++) { for(int j=i+1;j<str.length();j++) { String sub = str.substring(i, j); //int a=i+sub.indexOf(sub.charAt(0)); int ind = str.indexOf(sub, i+1); if(ind!=-1 && sub.length()>len ) { len = sub.length(); } } } System.out.println(len); // TODO code application logic here } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class P23A { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); int max = 0; for(int i = 0; i < s.length(); i++) for(int k = s.length(); k > max + i; k--) if(s.substring(i + 1).contains(s.substring(i,k))) max = k - i; System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
//package timus; import java.io.BufferedReader; 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.Reader; import java.io.StreamTokenizer; import java.io.Writer; import java.math.BigInteger; import java.util.Arrays; public class Abra { public static void main(String[] args) throws IOException { new Abra().run(); } StreamTokenizer in; PrintWriter out; boolean oj; void init() throws IOException { oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader( "input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); in = new StreamTokenizer(new BufferedReader(reader)); out = new PrintWriter(writer); } void run() throws IOException { long beginTime = System.currentTimeMillis(); init(); solve(); out.flush(); } void printMem() { if (!oj) { System.out.println("Memory used = " + (Runtime.getRuntime().totalMemory() - Runtime .getRuntime().freeMemory())); } } 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; } double nextDouble() throws IOException { in.nextToken(); return in.nval; } long deg(long x, long y) { long a = x; for (long i = 2; i <= y; i++) { a *= x; } return a; } long fact(long x) { long a = 1; for (long i = 2; i <= x; i++) { a *= i; } return a; } long digitSum(String x) { long a = 0; for (int i = 0; i < x.length(); i++) { a += x.codePointAt(i) - 48; } return a; } long digitSum(long x) { long a = 0; while (x > 0) { a += x % 10; x /= 10; } return a; } long digitMul(long x) { long a = 1; while (x > 0) { a *= x % 10; x /= 10; } return a; } int digitCubesSum(int x) { int a = 0; while (x > 0) { a += (x % 10) * (x % 10) * (x % 10); x /= 10; } return a; } double pif(double ax, double ay, double bx, double by) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); } double getPosPart(double x) { if (x <= 0) return 0; else return x; } double max(double x, double y) { if (x > y) return x; else return y; } long gcd(long a, long b) { if (a < b) { long c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { long c = b; b = a; a = c; } } return b; } int gcd(int a, int b) { if (a < b) { int c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { int c = b; b = a; a = c; } } return b; } long lcm(long a, long b) throws IOException { return a * b / gcd(a, b); } int lcm(int a, int b) throws IOException { return a * b / gcd(a, b); } int countOccurences(String x, String y) { int a = 0, i = 0; while (true) { i = y.indexOf(x); if (i == -1) break; a++; y = y.substring(i + 1); } return a; } int[] primes; int findPrimes(int x) { boolean[] forErato = new boolean[x]; primes = new int[x]; int l = 0, j = 0; for (int i = 2; i < x; i++) { if (forErato[i]) continue; l++; primes[l] = i; j = i * 2; while (j < x) { forErato[j] = true; j += i; } } return l; } int rev(int x) { int a = 0; while (x > 0) { a = a * 10 + x % 10; x /= 10; } return a; } class myDate { int d, m, y; public myDate(int da, int ma, int ya) { d = da; m = ma; y = ya; } int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; void inc() { if ((d == 31) && (m == 12)) { y++; d = 1; m = 1; } else { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { ml[1] = 29; } if (d == ml[m - 1]) { m++; d = 1; } else d++; } } } int partition(int n, int l, int m) {// n - sum, l - length, m - every part // <= m if (n < l) return 0; if (n < l + 2) return 1; if (l == 1) return 1; int c = 0; for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) { c += partition(n - i, l - 1, i); } return c; } String s; int l; void solve() throws IOException { s = nextString(); l = s.length(); int max = 0; for (int i = 0; i < l - 1; i++) { for (int j = i + 1; j < l; j++) { if (countOccurences(s.substring(i, j), s) > 1) if (j - i > max) max = j - i; } } out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES