diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5724e6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,54 @@ +# Credit to: erayaraz10@ +# https://medium.com/@erayaraz10/gitignore-file-examples-and-description-d2fecbd5697 + +# Ignore all .log files +*.log + +# Ignore the local.properties file +local.properties + +# Ignore all files in the bin and config directories +bin/ +config/ + +# Ignore all .impex and .hmc.xml files +*.impex +*.hmc.xml + +# Ignore the .idea directory created by IntelliJ IDEA +.idea/ + +# Ignore all .class files generated by the build process +**/*.class + +*.classpath +**/*.iml +rebel.xml +build.xml +Generated*.java +platformhome.properties +*testclasses.xml +extensioninfo.xsd +*hmc.jar +hmc.xsd +items.xsd +beans.xsd +ruleset.xml +base.properties + +# Addon specific copy folders +**/_ui/addons +**/views/addons +**/tld/addons +**/tags/addons +**/messages/addons +*_bof.jar +**/web/commonwebsrc +**/.settings/*.prefs +!**/.settings/org.eclipse.core.resources.prefs +!**/.settings/org.eclipse.jdt.core.prefs +!**/.settings/org.eclipse.jdt.ui.prefs +**/.idea/* +**/eclipsebin/* +**/.DS_Store +/**/node_modules/ diff --git a/Algorithms/AllPairShortestPath.java b/Algorithms/AllPairShortestPath.java new file mode 100644 index 0000000..c566699 --- /dev/null +++ b/Algorithms/AllPairShortestPath.java @@ -0,0 +1,149 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; +import utils.io.FastReader; +/* + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : All Pair Shortest Path + * Platform : Codeforces + * Ref : Time Complexity: O(N^3), Space Complexity: O(N^2) + */ + +class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + private final int BUFFER = 100005; + + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + final int MAX_N = 100; + long cost[][] = new long[MAX_N + 1][MAX_N + 1]; + long weight[][] = new long[MAX_N + 1][MAX_N + 1]; + + void run()throws Exception{ + int n = i(); + int ans = 0; + initialize(); + out.write(""+ans+"\n"); + } + + void initialize(){ + for(int i = 1; i <= MAX_N; i++){ + for(int j = 1; j <= MAX_N; j++){ + weight[i][j] = INF_L; + if(i==j)weight[i][j] = 0L; + } + } + } + + void allPairShortestPath(int n){ + for (int i = 1; i <= n; i++){ + for (int j = 1; j <= n; j++){ + cost[i][j] = weight[i][j]; + } + } + // order matters: k->i->j + for(int k = 1; k <= n; k++){ + for (int i = 1; i <= n; i++){ + for (int j = 1; j <= n; j++){ + if(cost[i][k] + cost[k][j] < cost[i][j]){ + cost[i][j] = cost[i][k] + cost[k][j]; + } + } + } + } + } + + int i()throws Exception{ + return in.nextInt(); + } + + long l()throws Exception{ + return in.nextLong(); + } + + double d()throws Exception{ + return in.nextDouble(); + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/All_Pair_shortest_Part.java b/Algorithms/All_Pair_shortest_Part.java deleted file mode 100644 index c13c60c..0000000 --- a/Algorithms/All_Pair_shortest_Part.java +++ /dev/null @@ -1,583 +0,0 @@ - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; -/* - * Author : joney_000[let_me_start][jaswantsinghyadav007@gmail.com] - * Algorithm : DP - * Platform : HackerCup - * - */ - -/* The Main Class */ - class A{ - - private InputStream inputStream ; - private OutputStream outputStream ; - private FastReader in ; - private PrintWriter out ; - /* - Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. - - */ - - //Critical Size Limit : 10^5 + 4 - private final int BUFFER = 100005; - private int tempints[] = new int[BUFFER]; - private long templongs[] = new long[BUFFER]; - private double tempdoubles[] = new double[BUFFER]; - private char tempchars[] = new char[BUFFER]; - private final long mod = 1000000000+7; - private final int INF = Integer.MAX_VALUE / 10; - private final long INF_L = Long.MAX_VALUE / 100; - - public A(){} - public A(boolean stdIO)throws FileNotFoundException{ - stdIO = false; - if(stdIO){ - inputStream = System.in; - outputStream = System.out; - }else{ - inputStream = new FileInputStream("manic_moving.txt"); - outputStream = new FileOutputStream("output.txt"); - } - in = new FastReader(inputStream); - out = new PrintWriter(outputStream); - - } - - long w[][] = new long[101][101]; - long cost[][] = new long[101][101]; - long dp[][] = new long[5004][2]; - int u[] = new int[5004]; - int v[] = new int[5004]; - - void run()throws Exception{ - - int tests = i(); - //once(); - for(int t = 1 ; t<= tests ; t++){ - clear(); - int n = i(); int m = i(); int k = i(); - for(int i = 1; i <= m; i++){ - int a = i(); int b = i(); - w[a][b] = w[b][a] = Math.min(w[a][b], i()); - } - for(int i = 1; i <= k; i++){ - u[i] = i(); v[i] = i(); - } - allPairShortestPath(n); - long ans = 0; - if(k == 1){ - ans = cost[1][u[1]] + cost[u[1]][v[1]]; - if(ans >= INF_L)ans = -1; - out.write("Case #"+t+": "+ans+"\n"); - continue; - } - for(int i = 1; i <= k; i++){ - if(i == 1){ - dp[i][0] = cost[1][u[1]] + cost[u[1]][v[1]]; - dp[i][1] = cost[1][u[1]] + cost[u[1]][u[i+1]] + cost[u[i+1]][v[1]]; - }else if(i == k){ - dp[i][0] = Math.min(dp[i-1][0] + cost[v[i-1]][u[i]] + cost[u[i]][v[i]] , dp[i-1][1] + cost[v[i-1]][v[i]]); - dp[i][1] = INF_L; - }else{ - dp[i][0] = Math.min(dp[i-1][0] + cost[v[i-1]][u[i]] + cost[u[i]][v[i]] , dp[i-1][1] + cost[v[i-1]][v[i]]); - dp[i][1] = Math.min(dp[i-1][0] + cost[v[i-1]][u[i]] + cost[u[i]][u[i+1]] + cost[u[i+1]][v[i]], dp[i-1][1] + cost[v[i-1]][u[i+1]] + cost[u[i+1]][v[i]]); - } - if(Math.min(dp[i][0],dp[i][1]) >= INF_L){ - ans = -1; - break; - } - ans = dp[k][0]; - } - out.write("Case #"+t+": "+ans+"\n"); - }//end tests - }//end run - void allPairShortestPath(int n){ - for (int i = 1; i <= n; i++){ - for (int j = 1; j <= n; j++){ - cost[i][j] = w[i][j]; - } - } - for (int k = 1; k <= n; k++){ - // Pick all vertices as source one by one - for (int i = 1; i <= n; i++){ - // Pick all vertices as destination for the - // above picked source - for (int j = 1; j <= n; j++){ - // If vertex k is on the shortest path from - // i to j, then update the value of dist[i][j] - if (cost[i][k] + cost[k][j] < cost[i][j]){ - cost[i][j] = cost[i][k] + cost[k][j]; - } - } - } - } - } - void clear(){ - for(int i = 0; i <= 101;i++)dp[i][0] = dp[i][1] = INF_L; - dp[0][0] = 0; - for(int i = 0; i <= 100; i++){ - for(int j = 0; j <= 100; j++){ - w[i][j] = INF_L; - if(i==j)w[i][j] = 0L; - } - } - } - -//****************************** My Utilities ***********************// - void print_r(Object...o){ - out.write("\n"+Arrays.deepToString(o)+"\n"); - out.flush(); - } - - int hash(String s){ - int base = 31; - int a = 31;//base = a multiplier - int mod = 100005;//range [0..100004] - long val = 0; - for(int i = 1 ; i<= s.length() ;i++){ - val += base * s.charAt(i-1); - base = ( a * base ) % 100005; - } - return (int)(val % 100005) ; - } - - boolean isPrime(long n){ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - int[] sieve(int n){ - - boolean isPrime[] = new boolean[n+1]; - int p[] = new int[n+1]; - int idx = 1; - // Put above 3 variables globle p[1..idx-1] - - - Arrays.fill(isPrime,true); - isPrime[0]=isPrime[1]=false; - for(int i = 2 ; i<= n ; i++){ - if(isPrime[i]){ - p[idx++] = i; - for(int j = 2* i ; j<= n ; j+=i ){ - isPrime[j] = false; - } - - } - - } - return p; - } - long gcd(long a , long b){ - if(b==0)return a; - return gcd(b , a%b); - } - long lcm(long a , long b){ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - long mulmod(long a , long b ,long mod){ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - long pow(long a , long b ,long mod){ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans); - if(ans >= mod )ans %= mod; - - if(b%2==1)ans = (a * ans); - if(ans >= mod )ans %= mod; - - return ans; - } - // 20*20 nCr Pascal Table - long[][] ncrTable(){ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } - //*******************************I/O******************************// - int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); - } - int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; - } - long l()throws Exception{ - return in.nextLong(); - } - long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; - } - - double d()throws Exception{ - return in.nextDouble(); - } - double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; - } - char c()throws Exception{ - return in.nextCharacter(); - } - char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; - } - String s()throws Exception{ - return in.nextLine(); - } - BigInteger bi()throws Exception{ - return in.nextBigInteger(); - } -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ private void closeResources(){ - out.flush(); - out.close(); - return; - } - public static void main(String[] args) throws java.lang.Exception{ - //let_me_start Shinch Returns - - - /* - // Old Reader Writer - BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); - BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); - */ - A driver = new A(true); - long start = System.currentTimeMillis(); - driver.run(); - long end = System.currentTimeMillis(); - //out.write(" Total Time : "+(end - start)+"\n"); - driver.closeResources(); - return ; - - } - -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[4*1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - /******************** Point class ***********************/ - -class Point implements Comparable{ - - public double x; - public double y; - - public Point(){ - this.x = 0; - this.y = 0; - } - public Point(double x , double y ){ - this.x = x; - this.y = y; - } - public int compareTo(Point p){ - if(this.x < p.x)return -1; - else if(this.x > p.x )return 1; - else { - if(this.y < p.y)return -1; - else if(this.y > p.y )return 1; - else return 0; - - } - } - public String toString(){ - return "x="+this.x+" y="+this.y; - } - -} - /******************** Pair class ***********************/ - -class Pair implements Comparable{ - public int id; - public long b; - public long a; - public long c; - public Pair(){ - this.id = 1000; - - this.a = 0; - this.b = 0; - this.c = 0; - } - public Pair(int id , long a,long b , long c ){ - this.id = id; - this.a = a; - this.b = b; - this.c = c; - } - public int compareTo(Pair p){ - if(this.a < p.a)return -1; - else if(this.a > p.a )return 1; - else { - if(this.b < p.b)return -1; - else if(this.b > p.b )return 1; - else return 0; - - } - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - -} diff --git a/A.java b/Algorithms/BFSAndLCA.java old mode 100644 new mode 100755 similarity index 56% rename from A.java rename to Algorithms/BFSAndLCA.java index 751e421..d5e04a3 --- a/A.java +++ b/Algorithms/BFSAndLCA.java @@ -1,468 +1,485 @@ - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; -/* - * Author : joney_000[let_me_start] - * Algorithm : Maximum matching for bipartite graph. Hopcroft-Karp algorithm in O(E * sqrt(V)) - * Platform : https://www.facebook.com/hackercup - * - */ - - class A { - - private InputStream inputStream ; - private OutputStream outputStream ; - private FastReader in ; - private PrintWriter out ; - /* - Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. - - */ - - //Critical Index Limit : [0..10^5 + 4] - private final int BUFFER = 100005; - private int tempints[] = new int[BUFFER]; - private long templongs[] = new long[BUFFER]; - private double tempdoubles[] = new double[BUFFER]; - private char tempchars[] = new char[BUFFER]; - private final long mod = 1000000000+7L; - private final int INF = Integer.MAX_VALUE / 10; - private final long INF_L = Long.MAX_VALUE / 10; - - public A(){} - public A(boolean stdIO)throws FileNotFoundException{ - //stdIO = false; - if(stdIO){ - inputStream = System.in; - outputStream = System.out; - }else{ - inputStream = new FileInputStream("laundro_matt.txt"); - outputStream = new FileOutputStream("output.txt"); - } - in = new FastReader(inputStream); - out = new PrintWriter(outputStream); - - } - - void run()throws Exception{ - - // int tests = i(); - // for(int t = 1 ; t <= tests ; t++){ - double n = d(); double m = d(); - long ans = Math.max(1, Math.ceil(n/2.0)) * Math.max(1, Math.ceil(m/2)); - out.write(""+ans+"\n"); - // }//end tests - }//end run - - void print_r(Object...o){ - out.write("\n"+Arrays.deepToString(o)+"\n"); - out.flush(); - } - - int hash(String s){ - int base = 31; - int a = 31;//base = a multiplier - int mod = 100005;//range [0..100004] - long val = 0; - for(int i = 1 ; i<= s.length() ;i++){ - val += base * s.charAt(i-1); - base = ( a * base ) % 100005; - } - return (int)(val % 100005) ; - } - - boolean isPrime(long n){ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - int[] sieve(int n){ - - boolean isPrime[] = new boolean[n+1]; - int p[] = new int[n+1]; - int idx = 1; - // Put above 3 variables globle p[1..idx-1] - - - Arrays.fill(isPrime,true); - isPrime[0]=isPrime[1]=false; - for(int i = 2 ; i<= n ; i++){ - if(isPrime[i]){ - p[idx++] = i; - for(int j = 2* i ; j<= n ; j+=i ){ - isPrime[j] = false; - } - - } - - } - return p; - } - long gcd(long a , long b){ - if(b==0)return a; - return gcd(b , a%b); - } - long lcm(long a , long b){ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - long mulmod(long a , long b ,long mod){ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - long pow(long a , long b ,long mod){ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans); - if(ans >= mod )ans %= mod; - - if(b%2==1)ans = (a * ans); - if(ans >= mod )ans %= mod; - - return ans; - } - // 20*20 nCr Pascal Table - long[][] ncrTable(){ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } - //*******************************I/O******************************// - int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); - } - int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; - } - long l()throws Exception{ - return in.nextLong(); - } - long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; - } - - double d()throws Exception{ - return in.nextDouble(); - } - double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; - } - char c()throws Exception{ - return in.nextCharacter(); - } - char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; - } - String s()throws Exception{ - return in.nextLine(); - } - BigInteger bi()throws Exception{ - return in.nextBigInteger(); - } -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ - -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ - private void closeResources(){ - out.flush(); - out.close(); - return; - } - public static void main(String[] args) throws java.lang.Exception{ - //let_me_start Shinch Returns - - A driver = new A(true); - long start = System.currentTimeMillis(); - driver.run(); - long end = System.currentTimeMillis(); - driver.closeResources(); - return ; - - } - -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[4*1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - /******************** Pair class ***********************/ - - class Pair implements Comparable{ - - public int a; - public int b; - - public Pair(){ - this.a = 0; - this.b = 0; - } - public Pair(int a, int b){ - this.a = a; - this.b = b; - } - public int compareTo(Pair p){ - if(this.b < p.b)return -1; - else if(this.b > p.b )return 1; - else { - if(this.a < p.a)return -1; - else if(this.a > p.a)return 1; - else return 0; - } - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; + +/* + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : BFS & LCA + * Platform : Codeforces + * Ref : + */ + +public class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + private final int BUFFER = 100005; + + private int auxInts[] = new int[BUFFER]; + private long auxLongs[] = new long[1]; + private double auxDoubles[] = new double[1]; + private char auxChars[] = new char[1]; + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + + int n, m; + + void run()throws Exception{ + clear(); + n = i(); m = n - 1; + for(int i = 1; i <= m; i++){ + int u = i(); int v = i(); + adj[u].add(v); + adj[v].add(u); + } + LinkedList adj0[] = getCopy(adj, n); // wow + bfs(adj0, 1, n); //Assuming that node 1 is the root node + long ans = 0; + out.write(""+ans+"\n"); + + }// end run + + void once(){ + + } + + int MAXN = 200005; + int depth[] = new int[MAXN + 1]; + int f[] = new int[MAXN + 1]; // f[i] = father of i + LinkedList adj[] = new LinkedList[MAXN + 1]; + boolean vis[] = new boolean[MAXN + 1]; + + void clear(){ + for(int i = 1; i <= MAXN; i++){ + adj[i] = new LinkedList(); + } + } + + // Maintain immutability + LinkedList[] getCopy(LinkedList[] graph, int n){ + LinkedList adjCopy[] = new LinkedList[n + 1]; + for(int i = 1; i <= n; i++){ + adjCopy[i] = new LinkedList(); + for(int x: graph[i]){ + adjCopy[i].add(x); + } + } + return adjCopy; + } + + void bfs(LinkedList graph[], int root, int n){ + LinkedList queue = new LinkedList(); + depth[root] = 0; + queue.add(root); + vis[root] = true; + while(!queue.isEmpty()){ + int u = queue.removeFirst(); + for(int v: graph[u]){ + if(!vis[v]){ + queue.add(v); + vis[v] = true; + depth[v] = 1 + depth[u]; + f[v] = u; + } + } + } + } + + int lca(int u, int v){ + while(u != v){ + if(depth[u] < depth[v]){ + v = f[v]; + }else if(depth[u] > depth[v]){ + u = f[u]; + }else{ + u = f[u]; + v = f[v]; + } + } + return u; + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + int[] is(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxInts[i] = in.nextInt(); + return auxInts; + } + + long l()throws Exception{ + return in.nextLong(); + } + + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxLongs[i] = in.nextLong(); + return auxLongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxDoubles[i] = in.nextDouble(); + return auxDoubles; + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxChars[i] = in.nextCharacter(); + return auxChars; + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } } \ No newline at end of file diff --git a/Algorithms/BFS_GRID.java b/Algorithms/BFS_GRID.java index f78bd22..aa3f281 100755 --- a/Algorithms/BFS_GRID.java +++ b/Algorithms/BFS_GRID.java @@ -1,516 +1,492 @@ //pakage joney_000[let_me_start] - +// import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /* * Author : joney_000[let_me_start] - * Algorithm : Not Specified - * Platform : CodeForces + * Algorithm : BinarySearch UpperBound & Lower Bound + * Platform : N/A + * */ - - /* The Main Class */ - class C -{ - public static InputStream inputStream = System.in; - public static OutputStream outputStream = System.out; - public static FastReader in = new FastReader(inputStream);; - public static PrintWriter out = new PrintWriter(outputStream);; - /* - Overhead [Additional Temporary Strorage] - */ - public static int tempints[] = new int[100005]; - public static long templongs[] = new long[100005]; - public static double tempdoubles[] = new double[100005]; - public static char tempchars[] = new char[100005]; - public static long mod = 1000000000+7; - - static int n = 0 , m = 0 ,si = 0 , sj = 0 , maxl = 0; - static int dx[] = {-1 ,-1 , -1 , 0 , 0, 1 ,1 ,1}; - static int dy[] = {-1 , 0 , 1 ,-1 , 1,-1 ,0 ,1}; - static ArrayList[] adj = null; - static boolean v[][] , mat[][]; - - public static void main(String[] args) throws java.lang.Exception{ - //let_me_start - /* BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); - BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); -3 -5 5 -....* -...*. -..*.. -...*. -....* -2 2 -*. -.. -3 3 -.*. -*** -.*. - */ - - int tests = i(); - mat = new boolean[1001][1001]; - v = new boolean[1001][1001]; - for(int t =1; t<= tests ;t++){ - - n = i(); m = i(); - - for(int i=0;i<=1000;i++){ - for(int j = 0 ; j<= 1000 ; j++){ - v[i][j] = false; - mat[i][j] = false; - } - } - - long ans=0; - si = 0 ; sj = 0 ; maxl=0; - for(int i=1;i<=n;i++){ - String s = s(); - for(int j = 1 ; j<= m ; j++){ - if(s.charAt(j-1)=='*'){ - mat[i][j] = true; - si = i; - sj = j; - } - } - } - bfs(si, sj); - for(int i=1;i<=n;i++){ - for(int j = 1 ; j<= m ; j++){ - v[i][j] = false; - } - } - bfs(si, sj); - ans = ( maxl + 1 ) ; - ans = ans / 2 + 1; - if(si==0||sj==0)ans = 0; - // out.write(" ans = "+ans+"\n"); - out.write(""+ans+"\n"); - out.flush(); - } - out.flush(); - return; - } - +public class A { -//****************************** Utilities ***********************// + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + /* + Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. + Size Limit : 10^5 + 4 + */ + private final int BUFFER = 10005; + private int tempints[] = new int[BUFFER]; + private long templongs[] = new long[BUFFER]; + private double tempdoubles[] = new double[BUFFER]; + private char tempchars[] = new char[BUFFER]; + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE / 10; + private final long INF_L = Long.MAX_VALUE / 10; - - boolean isValid(int i , int j){ - if(i<=n && i>=1 && j <= m && j>= 1 && (!v[i][j]) )return true; - else return false; - } - void bfs(int xroot, int yroot){ - - LinkedList xq = new LinkedList(); - LinkedList yq = new LinkedList(); - - int l = 0;//level and will be marked at the time of adding into queue - LinkedList level_q = new LinkedList(); - xq.add(xroot);yq.add(yroot); - v[xroot][yroot]=true; - //level[root]=0; - int temp_l = 0; - level_q.add(0); - while(!xq.isEmpty()){ - - int ux = xq.removeFirst(); //first - int uy = yq.removeFirst(); //first - l = level_q.removeFirst(); - - //level[u] = l; - for(int i = 0 ; i<= 7 ; i++){ - int vx = ux+dx[i] ; int vy = uy+dy[i]; - if(isValid(vx ,vy) ){ - v[vx][vy]=true; - if(mat[vx][vy]){ - temp_l = Math.max(l+1 , temp_l); - si = ux ; sj = uy; - } - xq.add(vx);yq.add(vy); - // adj[idx(ux,uy)].add(idx(vx , vy)); - // adj[idx(vx , vy)].add(idx(ux,uy)); - level_q.add(l+1); - // f[v]=u; - // level[v]=l+1; - } - } + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("output.txt"); + outputStream = new FileOutputStream("output1.txt"); } - maxl = Math.max(temp_l , maxl); - //out.write("\n first max level = "+l + " f_end ( x ="+ si+" y="+sj+")\n"); - out.flush(); - return ; - - } - public static boolean isPrime(long n)throws Exception{ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + + } + int n, m, q; + // 8 Dir + // int dx[] = {-1 ,-1 , -1 , 0 , 0, 1 ,1 ,1}; + // int dy[] = {-1 , 0 , 1 ,-1 , 1,-1 ,0 ,1}; + // 4 Dir + int dx[] = {-1, 1, 0, 0}; + int dy[] = { 0, 0, 1, -1}; + + int cnt[][] = new int[1005][1005]; + + void run()throws Exception{ + // int tests = i(); + // for(int t = 1 ; t <= tests; t++){ + n = i(); m = i(); q = i(); + clear(); + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= m; j++){ + char ch = c(); + mat[i][j] = ch; + } + } + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= m; j++){ + if(mat[i][j] == '.' && !vis[i][j])bfs(i, j); + } + } + for(int i = 1; i <= q; i++){ + out.write(""+cnt[i()][i()]+"\n"); + } + + // } + }// end run + + boolean vis[][] = new boolean[1005][1005]; + char mat[][] = new char[1005][1005]; + + void clear(){ + } - return true; - } - // sieve - public static int[] primes(int n)throws Exception{ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); - boolean arr[] = new boolean[n+1]; - Arrays.fill(arr,true); - arr[1]=false; - for(int i=2;i<=Math.sqrt(n);i++){ - if(!arr[i])continue; - for(int j = 2*i ;j<=n;j+=i){ - arr[i]=false; + + boolean isValid(int i , int j){ + if(i <= n && i >= 1 && j <= m && j>= 1 && (!vis[i][j]))return true; + else return false; } + + void bfs(int xroot, int yroot){ + + LinkedList xq = new LinkedList(); + LinkedList yq = new LinkedList(); + + // int l = 0;//level and will be marked at the time of adding into queue + LinkedList level_q = new LinkedList(); + xq.add(xroot); + yq.add(yroot); + vis[xroot][yroot] = true; + //level[root] = 0; + level_q.add(0); + + while(!xq.isEmpty()){ + + int ux = xq.removeFirst(); //first + int uy = yq.removeFirst(); //first + // l = level_q.removeFirst(); + //level[u] = l; + for(int i = 0 ; i <= 3 ; i++){ + int vx = ux + dx[i] ; + int vy = uy + dy[i]; + if(isValid(vx ,vy) && mat[vx][vy] == '.'){ + vis[vx][vy] = true; + xq.add(vx); yq.add(vy); + + // level_q.add(l+1); + // f[v] = u; + // level[v] = l+1; + } + } + } + } - LinkedList ll = new LinkedList(); - for(int i=1;i<=n;i++){ - if(arr[i])ll.add(i); + + long gcd(long a , long b){ + if(b==0)return a; + return gcd(b , a%b); + } + + long lcm(long a , long b){ + if(a==0||b==0)return 0; + return (a*b)/gcd(a,b); + } + + long mulmod(long a , long b ,long mod){ + if(a==0||b==0)return 0; + if(b==1)return a; + long ans = mulmod(a,b/2,mod); + ans = (ans*2)% mod; + if(b%2==1)ans = (a + ans)% mod; + return ans; } - n = ll.size(); - int primes[] = new int[n+1]; - for(int i=1;i<=n;i++){ - primes[i]=ll.removeFirst(); + long pow(long a , long b ,long mod){ + if(b==0)return 1; + if(b==1)return a; + long ans = pow(a,b/2,mod); + ans = (ans * ans); + if(ans >= mod )ans %= mod; + + if(b%2==1)ans = (a * ans); + if(ans >= mod )ans %= mod; + + return ans; } - return primes; - } - public static long gcd (long a , long b)throws Exception{ - if(b==0)return a; - return gcd(b , a%b); - } - public static long lcm (long a , long b)throws Exception{ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - public static long mulmod(long a , long b ,long mod)throws Exception{ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - public static long pow(long a , long b ,long mod)throws Exception{ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans)% mod; - if(b%2==1)ans = (a * ans)% mod; - return ans; - } - // 20*20 nCr Pascal Table - public static long[][] ncrTable()throws Exception{ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} + for(int j=0;j<=20 ;j++){ + for(int i=j+1;i<= 20 ;i++){ + ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; + } + } + return ncr; + } + //*******************************I/O******************************// + int i()throws Exception{ + //return Integer.parseInt(br.readLine().trim()); + return in.nextInt(); } - return ncr; - } -//*******************************I/O******************************// -public static int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); -} -public static int[] is(int n)throws Exception{ + int[] is(int n)throws Exception{ //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; -} -public static long l()throws Exception{ - return in.nextLong(); -} -public static long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; -} - -public static double d()throws Exception{ - return in.nextDouble(); -} -public static double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; -} -public static char c()throws Exception{ - return in.nextCharacter(); -} -public static char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; -} -public static String s()throws Exception{ - return in.nextLine(); -} -public static BigInteger bi()throws Exception{ - return in.nextBigInteger(); -} + for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); + return tempints; + } + long l()throws Exception{ + return in.nextLong(); + } + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); + return templongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); + return tempdoubles; + } + char c()throws Exception{ + return in.nextCharacter(); + } + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); + return tempchars; + } + String s()throws Exception{ + return in.nextLine(); + } + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } //***********************I/O ENDS ***********************// //*********************** 0.3%f [precision]***********************// /* roundoff upto 2 digits double roundOff = Math.round(a * 100.0) / 100.0; or System.out.printf("%.2f", val); - + */ /* print upto 2 digits after decimal val = ((long)(val * 100.0))/100.0; -*/ -} +*/ + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + public static void main(String[] args) throws java.lang.Exception{ + //let_me_start Shinch Returns + + + /* + // Old Reader Writer + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); + BufferedReader br=new BufferedReader(new FileReader("input.txt")); + BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); + */ + A driver = new A(true); + + driver.run(); -class FastReader{ + driver.closeResources(); + return ; - private boolean finished = false; + } - private InputStream stream; - private byte[] buf = new byte[1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; + } - public FastReader(InputStream stream){ - this.stream = stream; - } + class FastReader{ - 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++]; - } + private boolean finished = false; - public int peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } + public FastReader(InputStream stream){ + this.stream = stream; + } - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } + public 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 String nextString(){ - 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 int peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } - public boolean isSpaceChar(int c){ - if (filter != null){ - return filter.isSpaceChar (c); - } - return isWhitespace (c); - } + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } - public static boolean isWhitespace(int c){ - return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; - } + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } + public String nextString(){ + 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 String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } + public boolean isSpaceChar(int c){ + if (filter != null){ + return filter.isSpaceChar (c); + } + return isWhitespace (c); + } - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } + public static boolean isWhitespace(int c){ + return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; + } - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } - public String next(){ - return nextString (); - } + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } - public SpaceCharFilter getFilter(){ - return filter; - } + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - /******************** Pair class ***********************/ - - class Pair implements Comparable{ - public int a; - public int b; - public Pair(){ - this.a = 0; - this.b = 0; - } - public Pair(int a,int b){ - this.a = a; - this.b = b; - } - public int compareTo(Pair p){ - if(this.a==p.a){ - return this.b-p.b; + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } + } + /******************** Pair class ***********************/ + + class Pair implements Comparable{ + public int a; + public int b; + public Pair(){ + this.a = 0; + this.b = 0; + } + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + public int compareTo(Pair p){ + if(this.b==p.b){ + return this.a-p.a; + } + return (this.b - p.b); + } + public String toString(){ + return "a="+this.a+" b="+this.b; } - return this.a-p.a; - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - + } diff --git a/Algorithms/BFS_and_LCA by Father.java b/Algorithms/BFS_and_LCA by Father.java deleted file mode 100755 index d2c79d4..0000000 --- a/Algorithms/BFS_and_LCA by Father.java +++ /dev/null @@ -1,498 +0,0 @@ -//pakage joney_000[let_me_start] - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; - /******************** Main Class ***********************/ - -class A -{ - public static InputStream inputStream = System.in; - public static OutputStream outputStream = System.out; - public static FastReader in = new FastReader(inputStream);; - public static PrintWriter out = new PrintWriter(outputStream);; - /* - Overhead [Additional Temporary Strorage] - */ - public static int tempints[] = new int[100005]; - public static long templongs[] = new long[100005]; - public static double tempdoubles[] = new double[100005]; - public static char tempchars[] = new char[100005]; - public static long mod = 1000000000+7; - - public static void main(String[] args)throws Exception{ - - //let_me_start - - int n = i();//m=n-1; - int k = i(); - ArrayList al[] = new ArrayList[k+1]; - for(int i =1;i<=k;i++)al[i]=new ArrayList(); - int root = i(); - - LinkedList adj[] = new LinkedList[n+1]; //Adjency List - for(int i=1;i<=n ;i++)adj[i]=new LinkedList(); //init List - int level[] = new int[n+1]; // level[i]= level of node i in the tree - int f[] = new int[n+1]; - Arrays.fill(f,-1); - int u=0,v=0; - int m = n-1;//edges - for(int i=1;i<=m;i++){ - - u=i(); - v=i(); - adj[u].add(v); - adj[v].add(u); - } - for(int i=1;i<=n;i++){ - al[i()].add(i); - } - - bfs(adj,root,level,f,n); - - int q = i(); - int temp=0,ans=0; - for(int i=1;i<=q;i++){ - int st = i(); int type = i(); - if(al[type].size()==0){ - out.write("-1"+"\n"); - continue; - } - int max=-1; - int ans_node=-1;int vv=0; - for(int j = 0;jmax){ - max= level[ans]; - ans_node = v; - }else if(level[ans]==max&& v adj[] ,int root ,int n){ - - boolean vis[] = new boolean[n+1]; - LinkedList q = new LinkedList(); - int l = 0;//level and will be marked at the time of adding into queue - LinkedList level_q = new LinkedList(); - q.add(root); - vis[root]=true; - level[root]=0; - level_q.add(0); - while(!q.isEmpty()){ - int u = q.removeFirst(); //first - l = level_q.removeFirst(); - level[u] = l; - for(int v: adj[u]){ - if(!vis[v]){ - vis[v]=true; - q.add(v); - level_q.add(l+1); - f[v]=u; - level[v]=l+1; - } - } - } - } - - - - -//****************************** Utilities ***********************// - - public static boolean isPrime(long n)throws Exception{ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - public static int[] primes(int n)throws Exception{ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); - boolean arr[] = new boolean[n+1]; - Arrays.fill(arr,true); - for(int i=1;i<=Math.sqrt(n);i++){ - if(!arr[i])continue; - for(int j = 2*i ;j<=n;j+=i){ - arr[i]=false; - } - } - LinkedList ll = new LinkedList(); - for(int i=1;i<=n;i++){ - if(arr[i])ll.add(i); - } - n = ll.size(); - - int primes[] = new int[n+1]; - for(int i=1;i<=n;i++){ - primes[i]=ll.removeFirst(); - } - return primes; - } - public static long gcd (long a , long b)throws Exception{ - if(b==0)return a; - return gcd(b , a%b); - } - public static long lcm (long a , long b)throws Exception{ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - public static long mulmod(long a , long b ,long mod)throws Exception{ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - public static double pow(double a , long b )throws Exception{ - if(b==0)return 1.0D; - if(b==1)return a; - double ans = pow(a,b/2); - ans = (ans * ans); - if(b%2==1)ans = (a * ans); - return ans; - } - public static long pow(long a , long b ,long mod)throws Exception{ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans)% mod; - if(b%2==1)ans = (a * ans)% mod; - return ans; - } - // 20*20 nCr Pascal Table - public static long[][] ncrTable()throws Exception{ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } -//*******************************I/O******************************// -public static int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); -} -public static int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; -} -public static long l()throws Exception{ - return in.nextLong(); -} -public static long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; -} - -public static double d()throws Exception{ - return in.nextDouble(); -} -public static double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; -} -public static char c()throws Exception{ - return in.nextCharacter(); -} -public static char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; -} -public static String s()throws Exception{ - return in.nextLine(); -} -public static BigInteger bi()throws Exception{ - return in.nextBigInteger(); -} -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - /******************** Pair class ***********************/ - - class Pair implements Comparable{ - public int a; - public int b; - public Pair(){ - this.a = 0; - this.b = 0; - } - public Pair(int a,int b){ - this.a = a; - this.b = b; - } - public int compareTo(Pair p){ - if(this.a==p.a){ - return this.b-p.b; - } - return this.a-p.a; - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - -} diff --git a/Algorithms/BIT-RangeUpdate.java b/Algorithms/BIT-RangeUpdate.java new file mode 100644 index 0000000..2e63ff2 --- /dev/null +++ b/Algorithms/BIT-RangeUpdate.java @@ -0,0 +1,448 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; + +/* + * Author : joney_000[let_me_start] + * Algorithm : Bit / fenwick tree + * Platform : Codeforces + * Ref : https://sanugupta.wordpress.com/2014/08/29/binary-indexed-tree-fenwick-tree/ + */ + +class Main{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + private final int BUFFER = 200005; + + private int auxInts[] = new int[BUFFER]; + private long auxLongs[] = new long[1]; + private double auxDoubles[] = new double[1]; + private char auxChars[] = new char[1]; + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public Main(){} + public Main(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + + void run()throws Exception{ + int tests = i(); + for(int test = 1; test <= tests; test++){ + int n = i(); + int a[] = new int[n + 1]; + + for(int i = 0; i <= MAX; i++)tree[i] = 0; + long ans = 0; + for(int i = 1; i <= n; i++){ + a[i] = i(); + update(tree, a[i], 1); // range update + ans += qry(tree, MAX) - qry(tree, a[i]); + } + out.write(""+ans+"\n"); + } + }// end run + + final int MAX = 10000000; + long tree[] = new long[MAX + 5]; + + void update(long tree[], int idx, long value){ + if(idx == 0){ + tree[idx] += value; + return; + } + while(idx <= MAX){ + tree[idx] += value; + idx += (idx & (-idx)); + } + } + + long qry(long tree[], int idx){ + long ret = tree[0]; + while(idx > 0){ + ret += tree[idx]; + idx -= (idx & (-idx)); + } + return ret; + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + int[] is(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxInts[i] = in.nextInt(); + return auxInts; + } + + long l()throws Exception{ + return in.nextLong(); + } + + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxLongs[i] = in.nextLong(); + return auxLongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxDoubles[i] = in.nextDouble(); + return auxDoubles; + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxChars[i] = in.nextCharacter(); + return auxChars; + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + Main driver = new Main(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/BIT.java b/Algorithms/BIT.java index 44705e1..a7b40a8 100755 --- a/Algorithms/BIT.java +++ b/Algorithms/BIT.java @@ -4,418 +4,463 @@ import java.math.*; /* - * Coded by : jaswant Singh - * Lang : Java - * Algorithm : Not Specified - * Date : 29/Nov/2015 - */ - class Solution implements Comparable{ - public int vertex; - public int weight; - //public provide flexibility to access from outside the the class - //at the cost of security - public Solution(){ - this.vertex = 0; - this.weight = 0; - } - public Solution(int node , int weight){ - this.vertex = node; - this.weight = weight; - } - @Override - public int compareTo(Solution e){ - if(this.weight 0){ - sum += tree[idx]; - idx -= (idx & -idx); + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + final int MAX_TREE_SIZE = 200000; + + void run()throws Exception{ + int n = i(); int q = i(); int m = i(); + int qry[][] = new int[3][q + 1];// 0=>l, 1=> r, 2=>val + int a[] = new int[n + 1]; + initializeTree(MAX_TREE_SIZE); + for(int i = 1; i <= n; i++){ + a[i] = i(); + update(tree, i, a[i]); // point update this time, + update(tree, i + 1, -a[i]); // if range qry than comment this line and res = qry(tree, idx) - qry(tree, idx - 1) + } + + for(int i = 1; i <= q; i++){ + qry[0][i] = i(); // l + qry[1][i] = i(); // r + qry[2][i] = i(); // value + } + + for(int i = 1; i <= q; i++){ + update(tree, qry[0][i], qry[2][i]); + update(tree, qry[1][i] + 1, qry[2][i]); // range [l , r] } - return sum; -} - - public static boolean isPrime(long n)throws Exception{ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - public static long gcd (long a , long b)throws Exception{ - if(b==0)return a; - return gcd(b , a%b); - } - public static long lcm (long a , long b)throws Exception{ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); //TAKE CARE OF Integer RANGE OVERFLOW - } - public static long mulmod(long a , long b ,long mod)throws Exception{ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - public static long pow(long a , long b ,long mod)throws Exception{ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans)% mod; - if(b%2==1)ans = (a * ans)% mod; - return ans; - } - // 20*20 nCr Pascal Table - public static long[][] ncrTable()throws Exception{ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } -// My I/O function // -public static int i()throws Exception{ - return in.nextInt(); //read a single Integer -} -public static int[] is(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); //read N integers - return tempints; -} -public static long l()throws Exception{ //read a single Long - return in.nextLong(); -} -public static long[] ls(int n)throws Exception{ //read N Long type digits - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; -} + for(int i = 1; i <= n; i++){ + long res = query(tree, i); // case of point qry + out.write(""+res+" "); + } -public static double d()throws Exception{ - return in.nextDouble(); -} -public static double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; -} -public static char c()throws Exception{ - return in.nextCharacter(); -} -public static char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; -} -public static String s()throws Exception{ - return in.nextLine(); -} -public static BigInteger bi()throws Exception{ - return in.nextBigInteger(); + }// end run + + private long []tree; + private int treeSize; + + // time and space O(treeSize) + private void initializeTree(int treeSize){ + this.treeSize = treeSize; + tree = new long[treeSize]; + } + + // range update, time: O(log treeSize) + private void update(long tree[], int idx, long value){ + while(idx < this.treeSize){ + tree[idx] += value; + idx += (idx & (-idx)); + } + } + + // range sum, time: O(log treeSize) + private long query(long tree[], int idx){ + long ret = 0; + while(idx > 0){ + ret += tree[idx]; + idx -= (idx & (-idx)); + } + return ret; + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + int[] is(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxInts[i] = in.nextInt(); + return auxInts; + } + + long l()throws Exception{ + return in.nextLong(); + } + + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxLongs[i] = in.nextLong(); + return auxLongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxDoubles[i] = in.nextDouble(); + return auxDoubles; + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxChars[i] = in.nextCharacter(); + return auxChars; + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + BIT driver = new BIT(true); + driver.run(); + driver.closeResources(); + } } -//*********************** for 0.2%f [precision data]***********************// - /* - * roundoff upto 2 digits - * double roundOff = Math.round(a * 100.0) / 100.0; - * or - * System.out.printf("%.2f", val); - * - */ -/* - *print upto 2 digits after decimal - *val = ((long)(val * 100.0))/100.0; - * -*/ +class FastReader{ - - 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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } } +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/BinaryLifting.java b/Algorithms/BinaryLifting.java new file mode 100644 index 0000000..b10844c --- /dev/null +++ b/Algorithms/BinaryLifting.java @@ -0,0 +1,66 @@ +import java.util.LinkedList; +/** +* Time: O(N log N + Q * log N), each query is answered in log N time. Space: O(N log N) +* Use: +* Your BinaryLifting object will be instantiated and called as such: +* BinaryLifting obj = new BinaryLifting(n, parent); +* int param_1 = obj.getKthAncestor(node,k); +* ref: https://leetcode.com/problems/kth-ancestor-of-a-tree-node/ and https://www.youtube.com/watch?v=oib-XsjFa-M +*/ +class BinaryLifting { + // preprocess + // O(N log N) + // precompute the answer for power of 2 + private int[][] atLevel; // atLevel[nodeId][level] means what is the predecessor at 2^level higher + private int MAX_LOG = 0; + boolean vis[]; + public BinaryLifting(int n, int[] parent) { + MAX_LOG = 0; + vis = new boolean[n]; + while(n >= (1 << MAX_LOG)){ + MAX_LOG++; + } + atLevel = new int[n][MAX_LOG]; + for(int nodeId = 0; nodeId < n; nodeId++){ + for(int level = 0; level < MAX_LOG; level++){ + atLevel[nodeId][level] = -1; + } + } + for(int nodeId = 1; nodeId <= n - 1; nodeId++){ + if(vis[nodeId])continue; + LinkedList unVisited = new LinkedList(); // linked list as a stack for unvisited node + int currentNode = nodeId; + while(currentNode != -1 && !vis[currentNode]){ + unVisited.addLast(currentNode); + currentNode = parent[currentNode]; + } + while(!unVisited.isEmpty()){ + int topUnvisitedNode = unVisited.removeLast(); + atLevel[topUnvisitedNode][0] = parent[topUnvisitedNode]; + for(int level = 1; level <= MAX_LOG - 1; level++){ + if(atLevel[topUnvisitedNode][level - 1] != -1){ + atLevel[topUnvisitedNode][level] = atLevel[atLevel[topUnvisitedNode][level - 1]][level - 1]; + }else{ + break; + } + } + vis[topUnvisitedNode] = true; + } + } + } + + public int getKthAncestor(int node, int k) { + int kthAncestor = node; + for(int level = MAX_LOG - 1; level >= 0; level--){ // at ancestor at 2^level + if((k & (1 << level)) > 0){ // check if ith bit is set + // every numer can be represented by sum of power of 2 + kthAncestor = atLevel[kthAncestor][level]; + if(kthAncestor == -1){ + break; + } + } + } + return kthAncestor; + } +} + diff --git a/Algorithms/BinarySearch.java b/Algorithms/BinarySearch.java new file mode 100755 index 0000000..34697d9 --- /dev/null +++ b/Algorithms/BinarySearch.java @@ -0,0 +1,410 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; + +/** + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : Binary Search + * Time : O(long n) Space : O(1) + * Platform : Codeforces + * Ref : N/A + */ + + public class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + private final int BUFFER = 100005; + + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; // for file io, set from main driver + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + void run()throws Exception{ + int n = i(); int m = i(); + long ans = 0; + out.write(""+ans+"\n"); + } + + long binarySearch(int A[], int n, int key){ + int m = 0; + int l = 1; int r = n; + while(l <= r){ + m = l + (r-l)/2; + if(A[m] == key){ // first comparison + return m; + }else if( A[m] < key ){ // second comparison + l = m + 1; + }else{ + r = m - 1; + } + } + return -1; + } + + void clear(){ + + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = mulMod(ans, ans, mod); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = mulMod(a, ans, mod); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + long l()throws Exception{ + return in.nextLong(); + } + + double d()throws Exception{ + return in.nextDouble(); + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/Binary_Iterative.java b/Algorithms/Binary_Iterative.java deleted file mode 100755 index d541ae7..0000000 --- a/Algorithms/Binary_Iterative.java +++ /dev/null @@ -1,80 +0,0 @@ -/* package joney_000 */ - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; - -//zee algorithm to find pattern P in the larger text T in O(|S|+|T|) - public class Main{ - - - public static void main(String[] args)throws Exception{ - - /* BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); - */ - BufferedReader br=new BufferedReader(new InputStreamReader(System.in),2000); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out),2000); - //int tests = Integer.parseInt(br.readLine()); - - int arr [] =new int[1000005]; - - //for(int t=0;t= mod)ans %= mod; + + if(b % 2 == 1)ans = mulMod(a, ans, mod); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + long l()throws Exception{ + return in.nextLong(); + } + + double d()throws Exception{ + return in.nextDouble(); + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/BitSet_SegmentTree.java b/Algorithms/BitSet_SegmentTree.java deleted file mode 100755 index c08c320..0000000 --- a/Algorithms/BitSet_SegmentTree.java +++ /dev/null @@ -1,288 +0,0 @@ -/* package joney_000 */ - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; -class FastReader{ - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - class A{ - - - public static void main(String[] args)throws Exception - - { - - /* BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); - */ - - InputStream inputStream = System.in; - OutputStream outputStream = System.out; - FastReader in = new FastReader(inputStream); - PrintWriter out = new PrintWriter(outputStream); - - //String[] s = br.readLine().split(" "); - int n = in.nextInt();int q = in.nextInt(); - BitSet bits = new BitSet(n);//false = tails; - - for(int qq=1;qq<=q;qq++){ - //s = br.readLine().split(" "); - int sgn = in.nextInt(); int i=in.nextInt();int j = in.nextInt(); - if(sgn!=1){ - - bits.flip(i,j+1); - }else{ - out.write(""+bits.get(i,j+1).cardinality()+"\n"); - } - - } - out.flush(); - - } - public static boolean isPrime(long n)throws Exception{ - if(n==1)return false; - if(n==2||n==3)return true; - for(int i=2;i<=Math.sqrt(n);i++){ - if(n%i==0)return false; - } - return true; - } - public static long gcd(long a, long b)throws Exception{ - if(b==0)return a; - return gcd(b,a%b); - } - public static long lcm(long a, long b)throws Exception{ - if(b==0||a==0)return 0; - return (a*b)/gcd(a,b); - } - public static long pow(long a,long b,long mod)throws Exception{ - if(b==1)return a%mod; - if(b==0)return 1; - long ans=pow(a,b/2,mod); - ans=(ans*ans)%mod; - if(b%2!=0)ans=(ans*a)%mod; - - return ans; - } - } //end of class - diff --git a/Algorithms/ComparableExample.java b/Algorithms/ComparableExample.java new file mode 100755 index 0000000..7e548e2 --- /dev/null +++ b/Algorithms/ComparableExample.java @@ -0,0 +1,15 @@ + +class Person implements Comparable{ + private int start, end, salary; + + public Person(int start, int end, int salary){ + this.start = start; + this.end = end; + this.salary = salary; + } + + @Override + public int compareTo(Person that){ + return this.start - that.start; + } +} diff --git a/Algorithms/ComparatorSnippet.java b/Algorithms/ComparatorSnippet.java new file mode 100644 index 0000000..bad4c3d --- /dev/null +++ b/Algorithms/ComparatorSnippet.java @@ -0,0 +1,39 @@ +class Developer{ + private int age; + + public Developer(int age){ + this.age = age; + } + + void setAge(int age){ + this.age = age; + } + public int getAge(){ + return age; + } +} + +class DevComparator implements Comparator { + @Override + public int compare(Developer firstValue, Developer secondValue){ + return Integer.compare(firstValue.getAge(), secondValue.getAge()); + } +} + +public class ComparatorSnippet{ + + public static void main(String... args)throws Exception{ + // way - 1 + // better if sorting criteria keeps changing + Developer[] devs = Collections.sort(listDevs, new Comparator() { + @Override + public int compare(Developer o1, Developer o2) { + return o1.getAge() - o2.getAge(); + } + }); + // way - 2 + devs = Collections.sort(listDevs, (Developer a , Developer b) -> Integer.compare(a.getAge(), b.getAge())); + // way - 3 + devs = Collections.sort(listDevs, new DevComparator()); + } +} \ No newline at end of file diff --git a/Algorithms/CycleDetection.java b/Algorithms/CycleDetection.java new file mode 100755 index 0000000..24f45c8 --- /dev/null +++ b/Algorithms/CycleDetection.java @@ -0,0 +1,488 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; + +/* + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : DFS or similar + * Platform : Codeforces + * Ref : Cycle detection in forest + */ + +class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + private final int BUFFER = 100005; + + private int auxInts[] = new int[BUFFER]; + private long auxLongs[] = new long[1]; + private double auxDoubles[] = new double[1]; + private char auxChars[] = new char[1]; + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + final int MAXN = (int)1e5; + // adj representation of graph + LinkedList [] adj = new LinkedList[MAXN + 1]; + boolean vis[] = new boolean[MAXN+1]; // to mark visited + + int n, m; + + void run()throws Exception{ + n = i(); m = i(); + clear(n); + + for(int e = 1; e <= m; e++){ + int u = i(); int v = i(); + adj[u].add(v); // directed graph + } + LinkedList[] adj0 = getCopy(adj, n); // maintaining mutability + boolean isCycle = false; + for(int i = 1; i <= n; i++){ + if(!vis[i]){ + isCycle = isCycle | isCycle(i, adj0); //PS: Not connected Graph: i.e. forest containing disconnected components + if(isCycle){ + break; + } + } + } + + if(isCycle){ + out.write("yes cycle\n"); + }else { + out.write("no cycle\n"); + } + } + + void clear(int n){ + for(int i = 1; i <= n; i++){ + adj[i] = new LinkedList(); + } + } + + // Maintain immutability + LinkedList[] getCopy(LinkedList[] adj, int n)throws Exception{ + LinkedList adjCopy[] = new LinkedList[n + 1]; + for(int i = 1; i <= n; i++){ + adjCopy[i] = new LinkedList(); + for(int x: adj[i]){ + adjCopy[i].add(x); + } + } + return adjCopy; + } + + // int []depth = new int[MAXN + 1]; + + boolean isCycle(int root, LinkedList[] adj)throws Exception{ + + LinkedList queue = new LinkedList(); //the stack + int currentDepth = 0; // level + queue.add(root); + vis[root] = true; + + while(!queue.isEmpty()){ + + int u = queue.getLast(); //top + //depth[u]= currentDepth; + if(adj[u].size() > 0){ + int v = adj[u].removeFirst(); + if(!vis[v]){ + queue.add(v); + currentDepth++; + vis[v] = true; + }else { + return true; + } + }else{ + int v = queue.removeLast(); + currentDepth--; + } + } + return false; + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + int[] is(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxInts[i] = in.nextInt(); + return auxInts; + } + + long l()throws Exception{ + return in.nextLong(); + } + + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxLongs[i] = in.nextLong(); + return auxLongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxDoubles[i] = in.nextDouble(); + return auxDoubles; + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxChars[i] = in.nextCharacter(); + return auxChars; + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} diff --git a/Algorithms/Cycle_Detection.java b/Algorithms/Cycle_Detection.java deleted file mode 100755 index 8cd42ad..0000000 --- a/Algorithms/Cycle_Detection.java +++ /dev/null @@ -1,452 +0,0 @@ -//pakage joney_000[let_me_start] - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; - /******************** Main Class ***********************/ - -class A -{ - public static InputStream inputStream = System.in; - public static OutputStream outputStream = System.out; - public static FastReader in = new FastReader(inputStream);; - public static PrintWriter out = new PrintWriter(outputStream);; - /* - Overhead [Additional Temporary Strorage] - */ - public static int tempints[] = new int[100005]; - public static long templongs[] = new long[100005]; - public static double tempdoubles[] = new double[100005]; - public static char tempchars[] = new char[100005]; - public static long mod = 1000000000+7; - -public static void main(String[] args) throws java.lang.Exception{ - //let_me_start - //int tests=i(); - //int arr[] = is(n); - //String ans = "No"; - - int n = i(); int m = i(); - LinkedList adj[] = new LinkedList[n+1]; - for(int i=1;i<=n;i++)adj[i]= new LinkedList(); - boolean visited[] = new boolean[n+1]; - for(int t=1;t<=m;t++){ - int a = i(); int b = i(); - adj[a].add(b); //only for directional graph - - } - boolean ans = false; - for(int i=1;i<=n;i++){ - if(!visited[i])ans = ans | dfs(adj,i,visited,n); //or ... the Graph is forest contains disconnected components - } - if(ans)out.write("yes");else out.write("no cycle"); - out.flush(); - - return; - } - - - - - -//****************************** Utilities ***********************// -//For an unweighted graph, DFS traversal of the graph produces the minimum spanning tree and all pair shortest path tree. -public static boolean dfs(LinkedList adj[] ,int root, boolean [] visited ,int n)throws Exception{ - - - LinkedList q = new LinkedList(); //the stack - int l = 0;//level - - q.add(root); - visited[root]=true; - - while(!q.isEmpty()){ - - int u = q.getLast(); //top - //level[u]=l; - - if(adj[u].size()>0){ - int v = adj[u].removeFirst(); - if(!visited[v]){ - q.add(v);l++; - visited[v]=true; - }else{ - return true; - } - - }else{ - - int v = q.removeLast(); - l--; - - } - - } - return false; -} - public static boolean isPrime(long n)throws Exception{ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - public static int[] primes(int n)throws Exception{ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); - boolean arr[] = new boolean[n+1]; - Arrays.fill(arr,true); - for(int i=1;i<=Math.sqrt(n);i++){ - if(!arr[i])continue; - for(int j = 2*i ;j<=n;j+=i){ - arr[i]=false; - } - } - LinkedList ll = new LinkedList(); - for(int i=1;i<=n;i++){ - if(arr[i])ll.add(i); - } - n = ll.size(); - - int primes[] = new int[n+1]; - for(int i=1;i<=n;i++){ - primes[i]=ll.removeFirst(); - } - return primes; - } - public static long gcd (long a , long b)throws Exception{ - if(b==0)return a; - return gcd(b , a%b); - } - public static long lcm (long a , long b)throws Exception{ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - public static long mulmod(long a , long b ,long mod)throws Exception{ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - public static long pow(long a , long b ,long mod)throws Exception{ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans)% mod; - if(b%2==1)ans = (a * ans)% mod; - return ans; - } - // 20*20 nCr Pascal Table - public static long[][] ncrTable()throws Exception{ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } -//*******************************I/O******************************// -public static int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); -} -public static int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; -} -public static long l()throws Exception{ - return in.nextLong(); -} -public static long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; -} - -public static double d()throws Exception{ - return in.nextDouble(); -} -public static double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; -} -public static char c()throws Exception{ - return in.nextCharacter(); -} -public static char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; -} -public static String s()throws Exception{ - return in.nextLine(); -} -public static BigInteger bi()throws Exception{ - return in.nextBigInteger(); -} -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - /******************** Pair class ***********************/ - - class Pair implements Comparable{ - public int a; - public int b; - public Pair(){ - this.a = 0; - this.b = 0; - } - public Pair(int a,int b){ - this.a = a; - this.b = b; - } - public int compareTo(Pair p){ - if(this.a==p.a){ - return this.b-p.b; - } - return this.a-p.a; - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - -} diff --git a/Algorithms/DFSAdjacencyList.java b/Algorithms/DFSAdjacencyList.java new file mode 100755 index 0000000..e1dc135 --- /dev/null +++ b/Algorithms/DFSAdjacencyList.java @@ -0,0 +1,523 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; +/* + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : DFS : depth first search in Liner Time and Space + * Platform : Codeforces + */ + +class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + /* + Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. + Size Limit : 10^5 + 4 + */ + private final int BUFFER = 5; + private int tempints[] = new int[BUFFER]; + private long templongs[] = new long[BUFFER]; + private double tempdoubles[] = new double[BUFFER]; + private char tempchars[] = new char[BUFFER]; + //private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE / 10; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("output.txt"); + outputStream = new FileOutputStream("output1.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + + } + + int n = 0, m = 0; + + void run()throws Exception{ + int tests = i(); + once(); + clear(); + n = i(); m = n - 1; + for(int i = 1; i <= m; i++){ + int u = i(); int v = i(); + adj[u].add(v); + adj[v].add(u); + } + LinkedList adj0[] = getCopy(adj, n); // wow + dfs(adj0, 1, n); //Assuming that node 1 is the root node + long ans = 0; + out.write(""+ans+"\n"); + + }// end run + + void once(){ + + } + + int MAXN = 200005; + int depth[] = new int[MAXN + 1]; + int f[] = new int[MAXN + 1]; // f[i] = parent of i + LinkedList adj[] = new LinkedList[MAXN + 1]; + boolean vis[] = new boolean[MAXN+1]; + + void clear(){ + for(int i = 1; i <= MAXN; i++){ + adj[i] = new LinkedList(); + } + } + + // Maintain immutability + LinkedList[] getCopy(LinkedList[] adj, int n)throws Exception{ + LinkedList adjCopy[] = new LinkedList[n + 1]; + for(int i = 1; i <= n; i++){ + adjCopy[i] = new LinkedList(); + for(int x: adj[i]){ + adjCopy[i].add(x); + } + } + return adjCopy; + } + + void dfs(LinkedList adj[], int root, int n)throws Exception{ + + LinkedList queue = new LinkedList(); + int currentDepth = 0; //level + queue.add(root); + vis[root] = true; + + while(!queue.isEmpty()){ + + int u = queue.getLast(); // The Stack + depth[u] = currentDepth; + + if(adj[u].size()>0){ + int v = adj[u].removeFirst(); + if(!vis[v]){ + queue.add(v); + currentDepth++; + vis[v] = true; + depth[v] = currentDepth; + // f[v] = u; + } + }else { + int v = queue.removeLast(); + currentDepth--; + } + } + } + //****************************** Gerenal Utilities ***********************// + + void print_r(Object... o){ + out.write("\n"+Arrays.deepToString(o)+"\n"); + out.flush(); + } + + boolean isPrime(long n){ + if(n==1)return false; + if(n<=3)return true; + if(n%2==0)return false; + for(int i=2 ;i <= Math.sqrt(n); i++){ + if(n%i==0)return false; + } + return true; + } + // sieve + int[] primes(int n){ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); + boolean arr[] = new boolean[n+1]; + Arrays.fill(arr,true); + arr[1]=false; + for(int i=2;i<=Math.sqrt(n);i++){ + if(!arr[i])continue; + for(int j = 2*i ;j<=n;j+=i){ + arr[j]=false; + } + } + LinkedList ll = new LinkedList(); + for(int i=1;i<=n;i++){ + if(arr[i])ll.add(i); + } + n = ll.size(); + + int primes[] = new int[n+1]; + for(int i=1;i<=n;i++){ + primes[i]=ll.removeFirst(); + } + return primes; +} +long gcd(long a , long b){ + if(b==0)return a; + return gcd(b , a%b); +} +long lcm(long a , long b){ + if(a==0||b==0)return 0; + return (a*b)/gcd(a,b); +} +long mulmod(long a , long b ,long mod){ + if(a==0||b==0)return 0; + if(b==1)return a; + long ans = mulmod(a,b/2,mod); + ans = (ans*2)% mod; + if(b%2==1)ans = (a + ans)% mod; + return ans; +} +long pow(long a , long b ,long mod){ + if(b==0)return 1; + if(b==1)return a; + long ans = pow(a,b/2,mod); + ans = (ans * ans); + if(ans >= mod )ans %= mod; + + if(b%2==1)ans = (a * ans); + if(ans >= mod )ans %= mod; + + return ans; +} + // 20*20 nCr Pascal Table +long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} + for(int j=0;j<=20 ;j++){ + for(int i=j+1;i<= 20 ;i++){ + ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; + } + } + return ncr; + } + //*******************************I/O******************************// + int i()throws Exception{ + //return Integer.parseInt(br.readLine().trim()); + return in.nextInt(); + } + int[] is(int n)throws Exception{ + //int arr[] = new int[n+1]; + for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); + return tempints; + } + long l()throws Exception{ + return in.nextLong(); + } + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); + return templongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); + return tempdoubles; + } + char c()throws Exception{ + return in.nextCharacter(); + } + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); + return tempchars; + } + String s()throws Exception{ + return in.nextLine(); + } + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } +//***********************I/O ENDS ***********************// +//*********************** 0.3%f [precision]***********************// +/* roundoff upto 2 digits + double roundOff = Math.round(a * 100.0) / 100.0; + or + System.out.printf("%.2f", val); + +*/ +/* + print upto 2 digits after decimal + val = ((long)(val * 100.0))/100.0; + +*/ + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + public static void main(String[] args) throws java.lang.Exception{ + //let_me_start Shinch Returns + + + /* + // Old Reader Writer + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); + BufferedReader br=new BufferedReader(new FileReader("input.txt")); + BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); + */ + A driver = new A(true); + + driver.run(); + + driver.closeResources(); + return ; + + } + + } + + class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } + } + /******************** Pair class ***********************/ + + class Pair implements Comparable{ + public int a; + public int b; + public int c; + public Pair(){ + this.a = 0; + this.b = 0; + } + public Pair(int a,int b, int c){ + this.a = a; + this.b = b; + this.c = c; + } + public int compareTo(Pair p){ + if(this.a==p.a){ + return this.b-p.b; + } + return p.a-this.a; + } + public String toString(){ + return "a="+this.a+" b="+this.b; + } + +} diff --git a/Algorithms/DFS_AdjLis_New.java b/Algorithms/DFS_AdjLis_New.java deleted file mode 100755 index 275994e..0000000 --- a/Algorithms/DFS_AdjLis_New.java +++ /dev/null @@ -1,321 +0,0 @@ - - -import io.FastReader; -import java.io.PrintWriter; - -import java.io.*; -import java.lang.*; -import java.util.*; -import java.math.*; - -class A { - FastReader in ; - PrintWriter out; - void set(FastReader in , PrintWriter out){ - this.in = in; - this.out = out; - } - private final int BUFFER = 200005; - private int []tempints = new int[BUFFER]; - private long []templongs = new long[BUFFER]; - private double []tempdoubles = new double[BUFFER]; - private char []tempchars = new char[BUFFER]; - private final long mod = 1000000000+7; - private final int INF = Integer.MAX_VALUE / 10; - private final long INF_L = Long.MAX_VALUE / 10; - boolean ans = false; - int a = 0; - int b = 0; - HashMap hm = new HashMap(); - long tot = 0; - void solve() { - set(in,out); - int n = i(); - LinkedList adj1[] = new LinkedList[n+1]; - LinkedList adj2[] = new LinkedList[n+1]; - - for(int i = 1 ; i <= n ; i++){ - adj1[i]= new LinkedList<>(); - adj2[i] = new LinkedList<>(); - } - int root = 0; - for(int i = 1 ; i <= n ; i++){ - int p = i(); int q = i(); - if(p !=0) { - adj1[i].add(p); - adj1[p].add(i); - adj2[i].add(p); - adj2[p].add(i); - }else{ - root = i; - } - c[i] = q; - tot += q; - } - dfs1(adj1, root, n); - clear(n); - dfs2(adj2, root, n); - if(ans && (a!=0 || b !=0)){ - out.write(""+a+" "+b+"\n"); - }else{ - out.write("-1\n"); - } - // out.write(""+ans+""); - // out.write(""+a+" "+b+"\n"); - } - void once(){ - - } - void clear(int n){ - for(int i = 1; i <= n; i++)vis[i] = false; - // for(int i = 1; i <= n; i++)out.write("c="+c[i]+"\n"); - } - int []c = new int[1000005]; - boolean []vis = new boolean[1000005]; - int []f = new int[1000005]; - void dfs1(LinkedList adj[] ,int root, int n){ - - LinkedList q = new LinkedList(); //the stack - int l = 0;//level - - q.add(root); - vis[root]=true; - f[root] = 0; - while(!q.isEmpty()){ - - int u = q.getLast(); //top - // level[u]=l; - - if(adj[u].size()>0){ - int v = adj[u].removeFirst(); - if(!vis[v]){ - q.add(v); - l++; - vis[v]=true; - f[v] = u; - } - - }else{ - - int v = q.removeLast(); - c[f[v]] += c[v]; // cum subtree sum - l--; - } - } - } - - void dfs2(LinkedList adj[] ,int root, int n){ - - LinkedList q = new LinkedList(); //the stack - int l = 0;//level - - q.add(root); - vis[root]=true; -// Pair p = (Pair)hm.get(c[root]); -// if(p == null || p.a == 0){ -// // -// }else{ -// p.a -= 1; -// p.b.removeFirst(); -// hm.put(c[root], p); -// } - while(!q.isEmpty()){ - - int u = q.getLast(); //top - // level[u]=l; - - if(adj[u].size()>0){ - int v = adj[u].removeFirst(); - if(!vis[v]){ - q.add(v); - l++; - vis[v]=true; - Pair p = (Pair)hm.get(c[v]); - if(p == null || p.a == 0){ - // - }else{ - p.a -= 1; - p.b.removeFirst(); - hm.put(c[v], p); - } - - } - - }else{ - - int v = q.removeLast(); - l--; - Pair p = (Pair)hm.get(c[v]); - if(p == null || p.a == 0){ - p = new Pair(); - p.a = 1; - p.b = new LinkedList<>(); - p.b.add(v); - }else{ - if((tot - 2 * c[v] ) == c[v]){ - ans = true; - a = v; - b = (Integer) p.b.getFirst(); - } - p.a += 1; - p.b.add(v); - hm.put(c[v], p); - } - } - - } - } - - //****************************** My Utilities ***********************// - void print_r(Object...o){ - out.write("\n"+Arrays.deepToString(o)+"\n"); - out.flush(); - } - - int hash(String s){ - int base = 31; - int a = 31;//base = a multiplier - int mod = 100005;//range [0..100004] - long val = 0; - for(int i = 1 ; i<= s.length() ;i++){ - val += base * s.charAt(i-1); - base = ( a * base ) % 100005; - } - return (int)(val % 100005) ; - } - - boolean isPrime(long n){ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - int[] sieve(int n){ - - boolean isPrime[] = new boolean[n+1]; - int p[] = new int[n+1]; - int idx = 1; - // Put above 3 variables globle p[1..idx-1] - - - Arrays.fill(isPrime,true); - isPrime[0]=isPrime[1]=false; - for(int i = 2 ; i<= n ; i++){ - if(isPrime[i]){ - p[idx++] = i; - for(int j = 2* i ; j<= n ; j+=i ){ - isPrime[j] = false; - } - - } - - } - return p; - } - long gcd(long a , long b){ - if(b==0)return a; - return gcd(b , a%b); - } - long lcm(long a , long b){ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - long mulmod(long a , long b ,long mod){ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - long pow(long a , long b ,long mod){ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans); - if(ans >= mod )ans %= mod; - - if(b%2==1)ans = (a * ans); - if(ans >= mod )ans %= mod; - - return ans; - } - // 20*20 nCr Pascal Table - long[][] ncrTable(){ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } - //*******************************I/O******************************// - int i(){ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); - } - int[] is(int n){ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; - } - long l(){ - return in.nextLong(); - } - long[] ls(int n){ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; - } - - double d(){ - return in.nextDouble(); - } - double[] ds(int n){ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; - } - char c(){ - return in.nextCharacter(); - } - char[] cs(int n){ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; - } - String s(){ - return in.nextLine(); - } - BigInteger bi(){ - return in.nextBigInteger(); - } - - - -} -class Pair implements Comparable{ - public int a; - public LinkedList b; - public Pair(){ - this.a = 0; - this.b = new LinkedList<>(); - } - public Pair(int a,LinkedList b){ - this.a = a; - this.b = b; - } - public int compareTo(Pair p){ - if(this.a==p.a){ - return this.b.size()-p.b.size(); - } - return this.a-p.a; - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - -} \ No newline at end of file diff --git a/Algorithms/DFS_Grid.java b/Algorithms/DFS_Grid.java new file mode 100755 index 0000000..9ba98b3 --- /dev/null +++ b/Algorithms/DFS_Grid.java @@ -0,0 +1,496 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; + +/* + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : DFS-Grid + * Platform : Codeforces + * Ref : + */ + +public class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + private final int BUFFER = 100005; + + private int auxInts[] = new int[BUFFER]; + private long auxLongs[] = new long[1]; + private double auxDoubles[] = new double[1]; + private char auxChars[] = new char[1]; + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + int n, m; + // 8 Dir + // int dx[] = {-1 ,-1 , -1 , 0 , 0, 1 ,1 ,1}; + // int dy[] = {-1 , 0 , 1 ,-1 , 1,-1 ,0 ,1}; + // 4 Dir + int dx[] = {-1, 1, 0, 0}; + int dy[] = { 0, 0, 1, -1}; + + void run()throws Exception{ + + n = i(); m = i(); + clear(); + + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= m; j++){ + char ch = c(); + mat[i][j] = ch; + } + } + int cnt = 0; + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= m; j++){ + if(mat[i][j] == '.' && !vis[i][j]){ + dfs(i, j); + cnt++; + } + } + } + int ans = cnt; + out.write(""+ans+"\n"); + // } + }// end run + + final int MAX_N = 1005; + boolean vis[][] = new boolean[MAX_N][MAX_N]; + char mat[][] = new char[MAX_N][MAX_N]; + + void clear(){ + + } + + boolean isValid(int i , int j){ + if(i <= n && i >= 1 && j <= m && j>= 1 && (!vis[i][j]))return true; + else return false; + } + + void dfs(int xroot, int yroot){ + + LinkedList xq = new LinkedList(); + LinkedList yq = new LinkedList(); + + // int l = 0;//level and will be marked at the time of adding into queue + LinkedList level_q = new LinkedList(); + xq.add(xroot); + yq.add(yroot); + vis[xroot][yroot] = true; + //level[root]=0; + //level_q.add(l); + + while(!xq.isEmpty()){ + + int ux = xq.getLast(); //first + int uy = yq.getLast(); //first + // l = level_q.removeFirst(); + //level[u] = l; + boolean noUnvisitedChild = true; + + for(int i = 0 ; i <= 3 ; i++){ + int vx = ux + dx[i] ; + int vy = uy + dy[i]; + if(isValid(vx ,vy) && mat[vx][vy]=='.'){ + + vis[vx][vy] = true; + xq.add(vx); yq.add(vy); // Path + + noUnvisitedChild = false; + // level_q.add(l+1); + // f[v] = u; + // level[v] = l+1; + } + } + if(noUnvisitedChild){ + xq.removeLast(); + yq.removeLast(); + } + } + + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + int[] is(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxInts[i] = in.nextInt(); + return auxInts; + } + + long l()throws Exception{ + return in.nextLong(); + } + + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxLongs[i] = in.nextLong(); + return auxLongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxDoubles[i] = in.nextDouble(); + return auxDoubles; + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)auxChars[i] = in.nextCharacter(); + return auxChars; + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/DSU.java b/Algorithms/DSU.java index 96909af..f160be3 100755 --- a/Algorithms/DSU.java +++ b/Algorithms/DSU.java @@ -1,530 +1,68 @@ - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; /* - * Author : joney_000[let_me_start][jaswantsinghyadav007@gmail.com] - * Algorithm : DSU O(log n) + path optimization - * Platform : Codeforces - * + * Author : joney_000[developer.jaswant@gmail.com] + * Algorithm : Disjoint Set Union O(log n) + path optimization + * Platform : Codeforces/Leetcode. eg. problem: https://leetcode.com/problems/satisfiability-of-equality-equations/ */ - -/* The Main Class */ - class A{ - - private InputStream inputStream ; - private OutputStream outputStream ; - private FastReader in ; - private PrintWriter out ; - /* - Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. - - */ - - //Critical Size Limit : 10^5 + 4 - private final int BUFFER = 100005; - private int tempints[] = new int[BUFFER]; - private long templongs[] = new long[BUFFER]; - private double tempdoubles[] = new double[BUFFER]; - private char tempchars[] = new char[BUFFER]; - private final long mod = 1000000000+7; - private final int INF = Integer.MAX_VALUE / 10; - private final long INF_L = Long.MAX_VALUE / 10; - - public A(){} - public A(boolean stdIO)throws FileNotFoundException{ - //stdIO = false; - if(stdIO){ - inputStream = System.in; - outputStream = System.out; - }else{ - inputStream = new FileInputStream("laundro_matt.txt"); - outputStream = new FileOutputStream("output.txt"); - } - in = new FastReader(inputStream); - out = new PrintWriter(outputStream); - - } - - void run()throws Exception{ - - // int tests = i(); - // once(); - // for(int t = 1 ; t<= tests ; t++){ - int n = i(); int m = i(); - init(n); - for(int q = 1 ; q <= m ; q++){ - int type = i(); - if(type ==1){ - //join - int a = i(); int b = i(); - join(a,b); - - - }else{ - int u = i(); - out.write("root of "+u+"is :"+root(u)+"\n"); - - } - } - - // }//end tests - }//end run - void once(){ - - } - - int f[] = new int[200005]; - int h[] = new int[200005]; - - void init(int n){ - for(int i = 1 ; i <= n ; i++){ - f[i] = i; - h[i] = 0; - } - } - int root(int i){ - - if (f[i] != i) - f[i] = root(f[i]); - - return f[i]; - } - void join(int x, int y){ - int xroot = root(x); - int yroot = root(y); - if (h[xroot] < h[yroot]) - f[xroot] = yroot; - else if (h[xroot] > h[yroot]) - f[yroot] = xroot; - else { - f[yroot] = xroot; - h[xroot]++; - } - } - -//****************************** My Utilities ***********************// - void print_r(Object...o){ - out.write("\n"+Arrays.deepToString(o)+"\n"); - out.flush(); - } - - int hash(String s){ - int base = 31; - int a = 31;//base = a multiplier - int mod = 100005;//range [0..100004] - long val = 0; - for(int i = 1 ; i<= s.length() ;i++){ - val += base * s.charAt(i-1); - base = ( a * base ) % 100005; - } - return (int)(val % 100005) ; - } - - boolean isPrime(long n){ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - int[] sieve(int n){ - - boolean isPrime[] = new boolean[n+1]; - int p[] = new int[n+1]; - int idx = 1; - // Put above 3 variables globle p[1..idx-1] - - - Arrays.fill(isPrime,true); - isPrime[0]=isPrime[1]=false; - for(int i = 2 ; i<= n ; i++){ - if(isPrime[i]){ - p[idx++] = i; - for(int j = 2* i ; j<= n ; j+=i ){ - isPrime[j] = false; - } - - } - - } - return p; - } - long gcd(long a , long b){ - if(b==0)return a; - return gcd(b , a%b); - } - long lcm(long a , long b){ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - long mulmod(long a , long b ,long mod){ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - long pow(long a , long b ,long mod){ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans); - if(ans >= mod )ans %= mod; - - if(b%2==1)ans = (a * ans); - if(ans >= mod )ans %= mod; - - return ans; - } - // 20*20 nCr Pascal Table - long[][] ncrTable(){ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } - //*******************************I/O******************************// - int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); - } - int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; - } - long l()throws Exception{ - return in.nextLong(); - } - long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; - } - - double d()throws Exception{ - return in.nextDouble(); - } - double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; - } - char c()throws Exception{ - return in.nextCharacter(); - } - char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; - } - String s()throws Exception{ - return in.nextLine(); - } - BigInteger bi()throws Exception{ - return in.nextBigInteger(); - } -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ private void closeResources(){ - out.flush(); - out.close(); - return; - } - public static void main(String[] args) throws java.lang.Exception{ - //let_me_start Shinch Returns - - - /* - // Old Reader Writer - BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); - BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); - */ - A driver = new A(true); - long start = System.currentTimeMillis(); - driver.run(); - long end = System.currentTimeMillis(); - //out.write(" Total Time : "+(end - start)+"\n"); - driver.closeResources(); - return ; - - } - -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[4*1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } +class DSU { + private int[] parentOf; + private int[] depth; + private int size; + + public DSU(int size) { + this.size = size; + this.depth = new int[size + 1]; + this.parentOf = new int[size + 1]; + clear(size); + } + + // reset + public void clear(int range) { + this.size = range; + for (int pos = 1; pos <= range; pos++) { + depth[pos] = 0; + parentOf[pos] = pos; + } + } + + // Time: O(log n), Auxiliary Space: O(1) + int getRoot(int node) { + int root = node; + // finding root + while (root != parentOf[root]) { + root = parentOf[root]; + } + // update chain for new parent + while (node != parentOf[node]) { + int next = parentOf[node]; + parentOf[node] = root; + node = next; + } + return root; + } + + // Time: O(log n), Auxiliary Space: O(1) + void joinSet(int a, int b) { + int rootA = getRoot(a); + int rootB = getRoot(b); + if (rootA == rootB) { + return; + } + if (depth[rootA] >= depth[rootB]) { + depth[rootA] = Math.max(depth[rootA], 1 + depth[rootB]); + parentOf[rootB] = rootA; + } else { + depth[rootB] = Math.max(depth[rootB], 1 + depth[rootA]); + parentOf[rootA] = rootB; + } + } + + int getNoOfTrees() { + int uniqueRoots = 0; + for (int pos = 1; pos <= size; pos++) { + if (pos == getRoot(pos)) { + uniqueRoots++;// root + } + } + return uniqueRoots; + } } - /******************** Pair class ***********************/ - - class Pair implements Comparable{ - public int id; - public long b; - public long a; - public long c; - public Pair(){ - this.id = 1000; - - this.a = 0; - this.b = 0; - this.c = 0; - } - public Pair(int id , long a,long b , long c ){ - this.id = id; - this.a = a; - this.b = b; - this.c = c; - } - public int compareTo(Pair p){ - if(this.a < p.a)return -1; - else if(this.a > p.a )return 1; - else { - if(this.b < p.b)return -1; - else if(this.b > p.b )return 1; - else return 0; - - } - } - public String toString(){ - return "a="+this.a+" b="+this.b; - } - -} diff --git a/Algorithms/Dijkstra.java b/Algorithms/Dijkstra.java index 553a011..ef256e1 100755 --- a/Algorithms/Dijkstra.java +++ b/Algorithms/Dijkstra.java @@ -3,108 +3,468 @@ import java.io.*; import java.math.*; -/* - * Coded by : Jaswant Singh - * Lang : Java - * Algorithm : Dijkstra - * Date : 3/march/2015 - */ - class Edge implements Comparable{ - public int vertex; - public long weight; - public long weight1; - public long diff; - //public provide flexibility to access from outside the the class - //at the cost of security - public Edge(){ - this.vertex = 0; - this.weight = 0L; - } - public Edge(int node , long weight){ - this.vertex = node; - this.weight = weight; - } - @Override - public int compareTo(Edge e){ - if(this.weight adj[]; - public static int source; - //Creating Reader-Writer Buffer of initial size 2000B - public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in),2000); - public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out),2000); - public static long INF = Long.MAX_VALUE/100; - public static int s[] = new int[100005]; - public static long d[] = new long[100005+1]; - static { - Arrays.fill(d,INF); - } - - public Djkstra(){ - } - public static void main(String []arg)throws Exception{ - - String[] s= br.readLine().split(" "); - int n = Integer.parseInt(s[0]); //no of edges - int m = Integer.parseInt(s[1]); //no of nodes - //creating the undirected graph - adj = new ArrayList[n+1]; //Adjacency list - for(int i=1;i<=n;i++)adj[i] = new ArrayList(); - for(int i=1;i<=m;i++){ - s = br.readLine().split(" "); - int u = Integer.parseInt(s[0]); - int v = Integer.parseInt(s[1]); - long w = Long.parseLong(s[2]); - adj[u].add(new Edge(v,w)); - adj[v].add(new Edge(u,w));//if the graph is undirected - } - int q = i(); - for(int i=1;i<=q;i++){ - - source = Integer.parseInt(br.readLine()); - - //Applying the Djkstra - djkstra(adj,source,n); - - } - - out.flush(); - return ; - } - public static void djkstra(ArrayList []adj,int source,int n)throws Exception{ - - // long d[] = new long[n+1]; // initializing the distance vector - boolean f[] = new boolean[n+1]; // initializing the fronter vector - - d[source] = 0L; - - PriorityQueue pq = new PriorityQueue(); - pq.add(new Edge(source,0L)); - - while(!pq.isEmpty()){ - - Edge e = pq.remove(); - int u = e.vertex; - if(f[u])continue; // the current node already in the fronter - for(int i=0;i[] getGraphFromEdges(Edge []edges, int n){ + LinkedList[] graph = new LinkedList[n + 1]; + for(int i = 1; i <= n; i++){ + graph[i] = new LinkedList(); + } + for(Edge edge: edges){ + graph[edge.from].add(new Vertex(edge.to, edge.weight)); + } + return graph; + } + + // basically running Dijkstra from root 1 + // Space: O(N) + // Time: O((V + E) log N) + private LinkedList getShortestPath(Edge[] edges, int rootNode, int n){ + boolean fronteer[] = new boolean[n + 1];// assuming base 1 index + int path[] = new int[n + 1]; + Arrays.fill(path, -1); + long distance[] = new long[n + 1]; + Arrays.fill(distance, Long.MAX_VALUE/10); + PriorityQueue pQueue = new PriorityQueue(n, (a, b) -> Long.compare(a.cost ,b.cost)); + fronteer[rootNode] = true; + distance[rootNode] = 0; + LinkedList[] graph = getGraphFromEdges(edges, n); + pQueue.add(new Vertex(1, 0)); + while(!pQueue.isEmpty()){ + Vertex u = (Vertex)pQueue.poll(); + for(Vertex v: graph[u.nodeId]){ + if(!fronteer[v.nodeId] && distance[u.nodeId] + v.cost < distance[v.nodeId]){ + distance[v.nodeId] = distance[u.nodeId] + v.cost; + path[v.nodeId] = u.nodeId; + pQueue.add(new Vertex(v.nodeId, distance[v.nodeId])); + } + } + fronteer[u.nodeId] = true;// add it to frounter + } + LinkedList shortestPath = new LinkedList<>(); + shortestPath.add(n); + int idx = n; + while(path[idx] != -1){ + shortestPath.addFirst(path[idx]); + idx = path[idx]; + } + return shortestPath; + } + + void run()throws Exception{ + // int tests = i(); + // for(int t = 1; t <= tests; t++){ + int n = i(); int m = i(); + Edge edges[] = new Edge [2 * m ]; + for(int i = 0; i < m; i++){ + int from = i(); int to = i(); int weight = i(); + edges[i] = new Edge(from, to, weight); + edges[m + i] = new Edge(to, from, weight); + } + LinkedList path = getShortestPath(edges, 1, n); + if(path.size() == 0 || path.getFirst() != 1){ + out.write("-1"); + return; + } + for(int x: path){ + out.write(""+ x +" "); + } + out.write("\n"); + // } + } + + void clear(){ + + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = mulMod(ans, ans, mod); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = mulMod(a, ans, mod); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + long l()throws Exception{ + return in.nextLong(); + } + + double d()throws Exception{ + return in.nextDouble(); + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + Solution driver = new Solution(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + @Override + public int compareTo(Pair other){ + return Integer.compare(this.a, other.a); + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} \ No newline at end of file diff --git a/Algorithms/EularTotient.java b/Algorithms/EularTotient.java new file mode 100644 index 0000000..48b9e68 --- /dev/null +++ b/Algorithms/EularTotient.java @@ -0,0 +1,28 @@ +package Algorithms; + +class EularTotient { + /* + * compute the eular totient(https://en.wikipedia.org/wiki/Euler%27s_totient_function) + * of the given numer, speeding up the computation when we have prime numbers + * + * time complexity: O(k log n) where k = no of prime factors + * this method is advantagious when we have large numbers whose prime factors + * are small numbers eg. eular totient of 16'402'500'000 = 2^5 * 3^8 * 5^7 can be computed + * in only 3 steps. + */ + private long totient(long n , long primes[]){ + long result = n; + for(int i=0; primes[i] <= n; i++) + { + if(n < primes[i]) + break; + if(n % primes[i] == 0) + result -= result / primes[i]; + while (n % primes[i] == 0) + n /= primes[i]; + } + if(n > 1) + result -= result / n; + return result; + } +} diff --git a/Algorithms/Euler Tocient .java b/Algorithms/Euler Tocient .java deleted file mode 100755 index 60b9bb2..0000000 --- a/Algorithms/Euler Tocient .java +++ /dev/null @@ -1,498 +0,0 @@ - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; -/* - * Author : joney_000[Jaswant Singh][jaswantsinghyadav007@gmail.com] - * Algorithm : euler tocient function phi in O(n * (sqrt(n)/10)) and devisiors in O(n*sqrt(n)) sqrt(n)/10 ~~=> no of prime numbers in [1..sqrt(n)] - * Platform : Facebook HackerCup - * - */ - - - class A { - - private InputStream inputStream ; - private OutputStream outputStream ; - private FastReader in ; - private PrintWriter out ; - /* - Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. - - */ - - //Critical Size Limit : 10^5 + 4 - private final int BUFFER = 100005; - private int tempints[] = new int[BUFFER]; - private long templongs[] = new long[BUFFER]; - private double tempdoubles[] = new double[BUFFER]; - private char tempchars[] = new char[BUFFER]; - private final long mod = 1000000000+7; - private final int INF = Integer.MAX_VALUE / 10; - private final long INF_L = Long.MAX_VALUE / 10; - - public A(){} - public A(boolean stdIO)throws FileNotFoundException{ - //stdIO = false; - if(stdIO){ - inputStream = System.in; - outputStream = System.out; - }else{ - inputStream = new FileInputStream("laundro_matt.txt"); - outputStream = new FileOutputStream("output.txt"); - } - in = new FastReader(inputStream); - out = new PrintWriter(outputStream); - - } - int N = 500001 ; int MAXN = 500001; - int phi[] = new int[MAXN + 1]; - int prime[] = new int[MAXN + 1]; - int sz=0; - long val[] = new long[MAXN+1]; - boolean mark [] = new boolean[MAXN+1]; - - void run()throws Exception{ - prec(); - - } - - int phi(int n) { - int res = n; - for (int i = 2; i * i <= n; i++) - if (n % i == 0) { - while (n % i == 0) - n /= i; - res -= res / i; - } - if (n > 1) - res -= res / n; - return res; - } - -//****************************** My Utilities ***********************// - void print_r(Object...o){ - out.write("\n"+Arrays.deepToString(o)+"\n"); - out.flush(); - } - long h[]; - void hash(String s){ - long base = 31; - long a = 31;//base = a multiplier - long mod = 1000000007;//range [0..100004] - long val = 0; - for(int i = 1 ; i<= s.length() ;i++){ - val += base * s.charAt(i-1); - h[i] = val; - base = ( a * base ) % mod; - } - //return (int)(val % 100005) ; - } - - boolean isPrime(long n){ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - int[] sieve(int n){ - - boolean isPrime[] = new boolean[n+1]; - int p[] = new int[n+1]; - int idx = 1; - // Put above 3 variables globle p[1..idx-1] - - Arrays.fill(isPrime,true); - isPrime[0]=isPrime[1]=false; - for(int i = 2 ; i<= n ; i++){ - if(isPrime[i]){ - p[idx++] = i; - for(int j = 2* i ; j<= n ; j+=i ){ - isPrime[j] = false; - } - } - } - return p; - } - long gcd(long a , long b){ - if(b==0)return a; - return gcd(b , a%b); - } - long lcm(long a , long b){ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - long mulmod(long a , long b ,long mod){ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - long pow(long a , long b ,long mod){ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans); - if(ans >= mod )ans %= mod; - - if(b%2==1)ans = (a * ans); - if(ans >= mod )ans %= mod; - - return ans; - } - // 20*20 nCr Pascal Table - long[][] ncrTable(){ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } - //*******************************I/O******************************// - int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); - } - int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; - } - long l()throws Exception{ - return in.nextLong(); - } - long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; - } - - double d()throws Exception{ - return in.nextDouble(); - } - double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; - } - char c()throws Exception{ - return in.nextCharacter(); - } - char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; - } - String s()throws Exception{ - return in.nextLine(); - } - BigInteger bi()throws Exception{ - return in.nextBigInteger(); - } -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ private void closeResources(){ - out.flush(); - out.close(); - return; - } - public static void main(String[] args) throws java.lang.Exception{ - //let_me_start Shinch Returns - - - /* - // Old Reader Writer - BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); - BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); - */ - A driver = new A(true); - long start = System.currentTimeMillis(); - driver.run(); - long end = System.currentTimeMillis(); - //out.write(" Total Time : "+(end - start)+"\n"); - driver.closeResources(); - return ; - - } - -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[4*1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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 peek(){ - if (numChars == -1){ - return -1; - } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } - } - return buf[curChar]; - } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); - } -} - /******************** Pair class ***********************/ - - class Pair implements Comparable{ - - public long b; - public long a; - public long c; - public long prev = 0;; - public Pair(){ - - - this.a = 0L; - this.b = 0L; - this.c = 0L; - } - public Pair(long a,long b , long c ){ - - this.a = a; - this.b = b; - this.c = c; - } - public int compareTo(Pair p){ - if(this.a < p.a)return -1; - else if(this.a > p.a )return 1; - else { - if(this.b < p.b)return -1; - else if(this.b > p.b )return 1; - else { - return 0; - } - - } - } - public String toString(){ - return "a="+this.a+" b="+this.b+" c="+this.c; - } - -} diff --git a/Algorithms/FastFourierTransform.java b/Algorithms/FastFourierTransform.java new file mode 100644 index 0000000..4db1cd0 --- /dev/null +++ b/Algorithms/FastFourierTransform.java @@ -0,0 +1,534 @@ +import java.lang.String; +import java.util.Vector; +import java.util.Arrays; + +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.OutputStream; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.PrintWriter; + +import java.util.InputMismatchException; + +import java.io.IOException; +import java.io.FileNotFoundException; + +import java.lang.Math; +import java.math.BigInteger; + +/* + * Author : joney_000[Jaswant Singh][E-mail: developer.jaswant@gmail.com] + * Algorithm : FFT-Fast Fourier Transform, Polynomial Multiplication Time: O(N log N) Space: O(N) , N = polynomial order + * Platform : Codeforces + * Ref : https://codeforces.com/blog/entry/43499 + * https://gist.github.com/meooow25/0d61a01c0621efde7a83e1ef1dce898d +**/ + +class FastFourierTransform{ + static long m1 = 1007, m2 = 1109; + + static void fft(double[] a, double[] b, boolean invert) { + int count = a.length; + for (int i = 1, j = 0; i < count; i++) { + int bit = count >> 1; + for (; j >= bit; bit >>= 1) + j -= bit; + j += bit; + if (i < j) { + double temp = a[i]; + a[i] = a[j]; + a[j] = temp; + temp = b[i]; + b[i] = b[j]; + b[j] = temp; + } + } + + for (int len = 2; len <= count; len <<= 1) { + int halfLen = len >> 1; + double angle = 2 * Math.PI / len; + if (invert) + angle = -angle; + double wLenA = Math.cos(angle); + double wLenB = Math.sin(angle); + for (int i = 0; i < count; i += len) { + double wA = 1; + double wB = 0; + for (int j = 0; j < halfLen; j++) { + double uA = a[i + j]; + double uB = b[i + j]; + double vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB; + double vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA; + a[i + j] = uA + vA; + b[i + j] = uB + vB; + a[i + j + halfLen] = uA - vA; + b[i + j + halfLen] = uB - vB; + double nextWA = wA * wLenA - wB * wLenB; + wB = wA * wLenB + wB * wLenA; + wA = nextWA; + } + } + } + + if(invert) { + for(int i = 0; i < count; i++) { + a[i] /= count; + b[i] /= count; + } + } + } + + static long[] multiply(long[] a, long[] b) { + int resultSize = Integer.highestOneBit(Math.max(a.length, b.length) - 1) << 2; + resultSize = Math.max(resultSize, 1); + double[] aReal = new double[resultSize]; + double[] aImaginary = new double[resultSize]; + double[] bReal = new double[resultSize]; + double[] bImaginary = new double[resultSize]; + for (int i = 0; i < a.length; i++) + aReal[i] = a[i]; + for (int i = 0; i < b.length; i++) + bReal[i] = b[i]; + fft(aReal, aImaginary, false); + fft(bReal, bImaginary, false); + + // Linear convolution + for (int i = 0; i < resultSize; i++) { + double real = aReal[i] * bReal[i] - aImaginary[i] * bImaginary[i]; + aImaginary[i] = aImaginary[i] * bReal[i] + bImaginary[i] * aReal[i]; + aReal[i] = real; + } + + fft(aReal, aImaginary, true); + long[] result = new long[resultSize]; + for (int i = 0; i < resultSize; i++) + result[i] = Math.round(aReal[i]); + return result; + } + + static long[] polynomialPow(long[] b, int pow){ + + long a[] = new long[b.length]; + a[0] = 1; + int k = pow; + while(k > 0){ + if(k % 2 == 1) + a = FastFourierTransform.multiply(a, b); + b = FastFourierTransform.multiply(b, b); + k /= 2; + } + return a; + } + +} +public class A{ + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + + private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + final int MAXN = 1001; + + + void run()throws Exception{ + + + + int n = i(); int k = i(); + + long st = System.currentTimeMillis(); + + long a[] = new long[MAXN]; + long b[] = new long[MAXN]; + + // for(int i = 0; i <= n; i++){ + // a[i] = (long)(Math.random() * 100000); + // } + + // for(int i = 0; i <= n; i++){ + // a[i] = (long)(Math.random() * 100000); + // } + + // long res[] = FastFourierTransform.multiply(a, b); + // long res[] = FastFourierTransform.polynomialPow(a, k); + + // for(int i = 0; i <= 2 * n ; i++)out.write(""+res[i]+" "); + + + + long end = System.currentTimeMillis(); + // out.write("\nres size = "+res.length+" , time = "+(end - st)/1000.0); + // out.flush(); + } + + void clear(){ + + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + + return ans; + } + + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + long l()throws Exception{ + return in.nextLong(); + } + + double d()throws Exception{ + return in.nextDouble(); + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + +// IMP: roundoff upto 2 digits +// double roundOff = Math.round(a * 100.0) / 100.0; +// or +// System.out.printf("%.2f", val); + +// print upto 2 digits after decimal +// val = ((long)(val * 100.0))/100.0; + + public static void main(String[] args) throws java.lang.Exception{ + + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int a,int b){ + this.a = a; + this.b = b; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} + diff --git a/Algorithms/Gemotry.java b/Algorithms/Gemotry.java index c5a7d7e..3f0b7df 100755 --- a/Algorithms/Gemotry.java +++ b/Algorithms/Gemotry.java @@ -63,29 +63,79 @@ void run()throws Exception{ void once(){ } - //double angleInTheta = (Math.toDegrees(Math.acos(crossProduct/(dist1*dist2)))) + // angle between OA and OB vector + double getAngle(Point o, Point a, Point b){ + // double dist1 = distance(o, a); // fix + // double dist2 = distance(o, b); + // + // double dotProduct = dot(o, a, b); + // double angleInTheta = (Math.toDegrees(Math.acos(dotProduct/(dist1*dist2)))); + + // double crossProduct = dot(o, a, b); + // double angleInTheta = (Math.toDegrees(Math.asin(crossProduct/(dist1*dist2)))); + + // above both wrong methods : there is a loss of precesion in sqrt(X) * sqrt(Y) i.e dist1 * dist2 + // + // better user below + // a.b sin@ = a X b + // a.b cos@ = a * b + // tan@ = cross(a, b)/dot(a, b) + + // In Radian + // if(b.x == 0 && b.y >= 0)return Math.PI/2; + // if(b.x == 0 && b.y < 0)return (3*Math.PI)/2; + // if(b.x >= 0 && b.y == 0)return 0; + // if(b.x < 0 && b.y == 0)return Math.PI; + + // In Degrees + // if(b.x == 0 && b.y >= 0)return 90; + // if(b.x == 0 && b.y < 0)return 270; + // if(b.x >= 0 && b.y == 0)return 0; + // if(b.x < 0 && b.y == 0)return 180; + // if(b.x < 0 && b.y > 0)angleInTheta = 180 + angleInTheta; // 2nd qdt + // if(b.x < 0 && b.y < 0)angleInTheta = 180 + angleInTheta; // 3rd qdt + // if(b.x > 0 && b.y < 0)angleInTheta = 360 + angleInTheta; // 4th qdt + + // No Need Of degree conversion to sort + + + // tan2 function handles 1st,2nd, 3rd, 4th qdt in it. + // No need of doing below qtr handling, Math.atan2 internally does it. + + // double angle = (double)Math.atan2(cross(o, a, b), dot(o, a, b)); // (y, x) arctan(y/x) + double angle = Math.atan2(cross(o, a, b), dot(o, a, b)); + + return angle; + } // 90 degree clockwise rotation : The new position of point M (h, k) will become M’ (k, -h). - //Compute the dot product AB _ BC + //Compute the dot product AB * AC double dot(Point A, Point B, Point C){ double AB[] = new double[2];//0=>x , 1=>y - double BC[] = new double[2]; + double AC[] = new double[2]; + // (X1, y1) AB[0] = B.x-A.x; // AB is vector : A vector defines (direction + Magnitude/Length) But not the start point or end point AB[1] = B.y-A.y; - BC[0] = C.x-B.x; - BC[1] = C.y-B.y; - double dot = AB[0] * BC[0] + AB[1] * BC[1]; + // (x2, y2) + AC[0] = C.x-A.x; + AC[1] = C.y-A.y; + // dot = x1 * x2 + y1 * y2; + double dot = AB[0] * AC[0] + AB[1] * AC[1]; return dot; } //Compute the cross product AB x AC double cross(Point A, Point B, Point C){ - double AB[] = new double[2];//0=>x , 1=>y - double AC[] = new double[2]; - AB[0] = B.x-A.x; - AB[1] = B.y-A.y; - AC[0] = C.x-A.x; - AC[1] = C.y-A.y; - double cross = AB[0] * AC[1] - AB[1] * AC[0]; - return cross; + double AB[] = new double[2];//0=>x , 1=>y + double AC[] = new double[2]; + // (X1, y1) + AB[0] = B.x-A.x; + AB[1] = B.y-A.y; + + // (X2, y2) + AC[0] = C.x-A.x; + AC[1] = C.y-A.y; + // cross = x1 * y2 - y1 * x2; + double cross = AB[0] * AC[1] - AB[1] * AC[0]; + return cross; } //Compute the distance from A to B double distance(Point A, Point B){ @@ -120,7 +170,7 @@ Point intersectionPoint(Point A , Point B , Point C , Point D , boolean isSegme double A2 = D.y-C.y; double B2 = C.x-D.x; - double C2 = A1*C.x+B1*C.y; + double C2 = A2*C.x+B2*C.y; double det = A1*B2 - A2*B1; if(det==0)return new Point(-INF,-INF);// Lines/seg are parallel @@ -143,10 +193,10 @@ Point intersectionPoint(Point A , Point B , Point C , Point D , boolean isSegme double getPolygonArea(Point[] polygon, int n){ double area = 0D; for(int i = 2 ; i <= n-1; i++){ - double traingleArea = cross(polygon[0],polygon[i],polygon[i+1])/2.0D; + double traingleArea = cross(polygon[1],polygon[i],polygon[i+1])// /2.0D; area += traingleArea; } - return Math.abs(area); + return Math.abs(area)/2.0D; } //****************************** My Utilities ***********************// diff --git a/Algorithms/HashSetComparator.java b/Algorithms/HashSetComparator.java index abd4bcb..7f4eda8 100755 --- a/Algorithms/HashSetComparator.java +++ b/Algorithms/HashSetComparator.java @@ -1,479 +1,34 @@ -//pakage joney_000[let_me_start] - -import java.util.*; -import java.lang.*; -import java.io.*; -import java.math.*; -/* - * Author : joney_000[let_me_start] - * Algorithm : Not Specified - * Platform : CodeForces - */ - - /* The Main Class */ - class C -{ - public static InputStream inputStream = System.in; - public static OutputStream outputStream = System.out; - public static FastReader in = new FastReader(inputStream);; - public static PrintWriter out = new PrintWriter(outputStream);; - /* - Overhead [Additional Temporary Strorage] - */ - public static int tempints[] = new int[100005]; - public static long templongs[] = new long[100005]; - public static double tempdoubles[] = new double[100005]; - public static char tempchars[] = new char[100005]; - public static long mod = 1000000000+7; - - public static void main(String[] args) throws java.lang.Exception{ - //let_me_start - /* BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); - BufferedReader br=new BufferedReader(new FileReader("input.txt")); - BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); - */ - - int tests = i(); - for(int t = 1 ; t<= tests ; t++){ - int n = i(); - HashMap hm1 = new HashMap(); - HashSet hx = new HashSet(); - HashSet hy = new HashSet(); - int a = 0 , b = 0 , c = 0 , aa = 0 , bb = 0; - int ans = 0 , g = 0; +class Pair { + public int a; + public int b; - hy.add(new Pair(a,c)); - Pair I = hm1.get(new Pair(aa ,bb )); - if(I == null){ - Pair p = new Pair(aa , bb); - if(c==0)g = 1; - p.s.add(new Pair(c, g)); - hm1.put(p , p); - }else{ - if(c==0)g = 1; - I.s.add(new Pair(c,g)); - hm1.put(I ,I); - } - - - /* Integer I = hm1.get(new Pair(a ,c )); - if(I == null){ - hm2.put(new Pair(a , c) ,1); - }else{ - hm2.put(new Pair(a , c) ,I.intValue()+1); - } - */ - } - // out.write("hx = "+hx.size()+" hy = "+hy.size()+"ans = "+ans+"\n"); - // Iterator it = hm1.entrySet().iterator(); - ans = Math.max(hx.size() , hy.size()); - /* - while (it.hasNext()) { - Pair pair = (Pair)it.next(); - - ans = Math.max(ans , (pair.s.size())); - } - */ - - Iterator it = hm1.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - // out.write(""+(Pair)pair.getKey()+" set size="+((Pair)pair.getKey()).s.size()+"\n"); - ans = Math.max(ans , ((Pair)pair.getKey()).s.size()); - } - - - - out.write(""+ans+"\n"); - } - - - out.flush(); - return; - } - - + public Pair(int a, int b){ + this.a = a; + this.b = b; + } - -//****************************** Utilities ***********************// - - public static boolean isPrime(long n)throws Exception{ - if(n==1)return false; - if(n<=3)return true; - if(n%2==0)return false; - for(int i=2 ;i <= Math.sqrt(n); i++){ - if(n%i==0)return false; - } - return true; - } - // sieve - public static int[] primes(int n)throws Exception{ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); - boolean arr[] = new boolean[n+1]; - Arrays.fill(arr,true); - arr[1]=false; - for(int i=2;i<=Math.sqrt(n);i++){ - if(!arr[i])continue; - for(int j = 2*i ;j<=n;j+=i){ - arr[i]=false; - } - } - LinkedList ll = new LinkedList(); - for(int i=1;i<=n;i++){ - if(arr[i])ll.add(i); - } - n = ll.size(); - - int primes[] = new int[n+1]; - for(int i=1;i<=n;i++){ - primes[i]=ll.removeFirst(); - } - return primes; - } - public static int gcd (int a , int b)throws Exception{ - if(b==0)return a; - return gcd(b , a%b); - } - public static long gcd (long a , long b)throws Exception{ - if(b==0)return a; - return gcd(b , a%b); - } - public static long lcm (long a , long b)throws Exception{ - if(a==0||b==0)return 0; - return (a*b)/gcd(a,b); - } - public static long mulmod(long a , long b ,long mod)throws Exception{ - if(a==0||b==0)return 0; - if(b==1)return a; - long ans = mulmod(a,b/2,mod); - ans = (ans*2)% mod; - if(b%2==1)ans = (a + ans)% mod; - return ans; - } - public static long pow(long a , long b ,long mod)throws Exception{ - if(b==0)return 1; - if(b==1)return a; - long ans = pow(a,b/2,mod); - ans = (ans * ans)% mod; - if(b%2==1)ans = (a * ans)% mod; - return ans; - } - // 20*20 nCr Pascal Table - public static long[][] ncrTable()throws Exception{ - long ncr[][] = new long[21][21]; - for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} - for(int j=0;j<=20 ;j++){ - for(int i=j+1;i<= 20 ;i++){ - ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; - } - } - return ncr; - } -//*******************************I/O******************************// -public static int i()throws Exception{ - //return Integer.parseInt(br.readLine().trim()); - return in.nextInt(); -} -public static int[] is(int n)throws Exception{ - //int arr[] = new int[n+1]; - for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); - return tempints; -} -public static long l()throws Exception{ - return in.nextLong(); -} -public static long[] ls(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); - return templongs; -} - -public static double d()throws Exception{ - return in.nextDouble(); -} -public static double[] ds(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); - return tempdoubles; -} -public static char c()throws Exception{ - return in.nextCharacter(); -} -public static char[] cs(int n)throws Exception{ - for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); - return tempchars; -} -public static String s()throws Exception{ - return in.nextLine(); -} -public static BigInteger bi()throws Exception{ - return in.nextBigInteger(); -} -//***********************I/O ENDS ***********************// -//*********************** 0.3%f [precision]***********************// -/* roundoff upto 2 digits - double roundOff = Math.round(a * 100.0) / 100.0; - or - System.out.printf("%.2f", val); - -*/ -/* - print upto 2 digits after decimal - val = ((long)(val * 100.0))/100.0; - -*/ -} - -class FastReader{ - - private boolean finished = false; - - private InputStream stream; - private byte[] buf = new byte[1024]; - private int curChar; - private int numChars; - private SpaceCharFilter filter; - - public FastReader(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; - } + @Override + public boolean equals(Object pair) { + if (pair == null) { + return false; } - return buf[curChar++]; - } - - public int peek(){ - if (numChars == -1){ - return -1; + Pair otherPair = (Pair)pair; + if (!(otherPair instanceof Pair)) { + return false; } - if (curChar >= numChars){ - curChar = 0; - try{ - numChars = stream.read (buf); - } catch (IOException e){ - return -1; - } - if (numChars <= 0){ - return -1; - } + if (this.a == otherPair.a && this.b == otherPair.b){ + return true; } - return buf[curChar]; + return false; } - - public int nextInt(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - int res = 0; - do{ - if(c==','){ - c = read(); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public long nextLong(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - long res = 0; - do{ - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } while (!isSpaceChar (c)); - return res * sgn; - } - - public String nextString(){ - 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; - } - - private String readLine0(){ - StringBuilder buf = new StringBuilder (); - int c = read (); - while (c != '\n' && c != -1){ - if (c != '\r'){ - buf.appendCodePoint (c); - } - c = read (); - } - return buf.toString (); - } - - public String nextLine(){ - String s = readLine0 (); - while (s.trim ().length () == 0) - s = readLine0 (); - return s; - } - - public String nextLine(boolean ignoreEmptyLines){ - if (ignoreEmptyLines){ - return nextLine (); - }else{ - return readLine0 (); - } - } - - public BigInteger nextBigInteger(){ - try{ - return new BigInteger (nextString ()); - } catch (NumberFormatException e){ - throw new InputMismatchException (); - } - } - - public char nextCharacter(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - return (char) c; - } - - public double nextDouble(){ - int c = read (); - while (isSpaceChar (c)) - c = read (); - int sgn = 1; - if (c == '-'){ - sgn = -1; - c = read (); - } - double res = 0; - while (!isSpaceChar (c) && c != '.'){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - res *= 10; - res += c - '0'; - c = read (); - } - if (c == '.'){ - c = read (); - double m = 1; - while (!isSpaceChar (c)){ - if (c == 'e' || c == 'E'){ - return res * Math.pow (10, nextInt ()); - } - if (c < '0' || c > '9'){ - throw new InputMismatchException (); - } - m /= 10; - res += (c - '0') * m; - c = read (); - } - } - return res * sgn; - } - - public boolean isExhausted(){ - int value; - while (isSpaceChar (value = peek ()) && value != -1) - read (); - return value == -1; - } - - public String next(){ - return nextString (); - } - - public SpaceCharFilter getFilter(){ - return filter; - } - - public void setFilter(SpaceCharFilter filter){ - this.filter = filter; - } - - public interface SpaceCharFilter{ - public boolean isSpaceChar(int ch); + + @Override + public int hashCode(){ + long hash = 31; + long mod = 1000000009; + hash = (hash + 97 * this.a) % mod; + hash = 31 * hash + 97 * this.b; + hash %= mod; + return (int)hash; } } - /******************** Pair class ***********************/ - -class Pair { - public int a; - public int b; - public Pair(int a, int b){ - this.a = a; - this.b = b; - } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Pair o = (Pair) obj; - if (( this.a == o.a) && (this.b==o.b)){ - return true; - } - return false; - } - - @Override - public int hashCode() { - long hash = 31; - hash = (hash + 97 * this.a)%1000000009; - hash = 31 * hash + 97 * this.b; - hash %= 1000000009; - return (int)hash; - } -} diff --git a/Algorithms/HungarianAlgorithm-MinCost-Maximal-Matching.java b/Algorithms/HungarianAlgorithm-MinCost-Maximal-Matching.java new file mode 100644 index 0000000..e3be7be --- /dev/null +++ b/Algorithms/HungarianAlgorithm-MinCost-Maximal-Matching.java @@ -0,0 +1,297 @@ +/* package whatever; // don't place package name! */ + +import java.util.*; +import java.lang.*; +import java.io.*; +import java.util.Arrays; +// (Min Cost Maximal Matching : HungarianAlgorithm , to solve max cost maximal +// matching you can change the cost matrix mat[i][j] = K - mat[i][j] or mat[i][j] = -mat[i][j] +class A +{ + public static void main (String[] args) throws java.lang.Exception + { + // The Cost Matrix + double mat[][] = { + {2, 1, 3}, + {1, 0, 2}, + {1, 2, 1}, + {3, 1, 2} + }; + HungarianAlgorithm hn = new HungarianAlgorithm(mat); + int res[] = hn.execute(); + for(int i = 0; i < res.length; i++){ + System.out.print("worker "+i+" assigned to complete job "+res[i]+"\n"); + } + } +} + +class HungarianAlgorithm { + public final double[][] costMatrix; + public final int rows, cols, dim; + public final double[] labelByWorker, labelByJob; + public final int[] minSlackWorkerByJob; + public final double[] minSlackValueByJob; + public final int[] matchJobByWorker, matchWorkerByJob; + public final int[] parentWorkerByCommittedJob; + public final boolean[] committedWorkers; + + /** + * Construct an instance of the algorithm. + * + * @param costMatrix + * the cost matrix, where matrix[i][j] holds the cost of assigning + * worker i to job j, for all i, j. The cost matrix must not be + * irregular in the sense that all rows must be the same length; in + * addition, all entries must be non-infinite numbers. + */ + public HungarianAlgorithm(double[][] costMatrix) { + this.dim = Math.max(costMatrix.length, costMatrix[0].length); + this.rows = costMatrix.length; + this.cols = costMatrix[0].length; + this.costMatrix = new double[this.dim][this.dim]; + for (int w = 0; w < this.dim; w++) { + if (w < costMatrix.length) { + if (costMatrix[w].length != this.cols) { + throw new IllegalArgumentException("Irregular cost matrix"); + } + for (int j = 0; j < this.cols; j++) { + if (Double.isInfinite(costMatrix[w][j])) { + throw new IllegalArgumentException("Infinite cost"); + } + if (Double.isNaN(costMatrix[w][j])) { + throw new IllegalArgumentException("NaN cost"); + } + } + this.costMatrix[w] = Arrays.copyOf(costMatrix[w], this.dim); + } else { + this.costMatrix[w] = new double[this.dim]; + } + } + labelByWorker = new double[this.dim]; + labelByJob = new double[this.dim]; + minSlackWorkerByJob = new int[this.dim]; + minSlackValueByJob = new double[this.dim]; + committedWorkers = new boolean[this.dim]; + parentWorkerByCommittedJob = new int[this.dim]; + matchJobByWorker = new int[this.dim]; + Arrays.fill(matchJobByWorker, -1); + matchWorkerByJob = new int[this.dim]; + Arrays.fill(matchWorkerByJob, -1); + } + + /** + * Compute an initial feasible solution by assigning zero labels to the + * workers and by assigning to each job a label equal to the minimum cost + * among its incident edges. + */ + protected void computeInitialFeasibleSolution() { + for (int j = 0; j < dim; j++) { + labelByJob[j] = Double.POSITIVE_INFINITY; + } + for (int w = 0; w < dim; w++) { + for (int j = 0; j < dim; j++) { + if (costMatrix[w][j] < labelByJob[j]) { + labelByJob[j] = costMatrix[w][j]; + } + } + } + } + + /** + * Execute the algorithm. + * + * @return the minimum cost matching of workers to jobs based upon the + * provided cost matrix. A matching value of -1 indicates that the + * corresponding worker is unassigned. + */ + public int[] execute() { + /* + * Heuristics to improve performance: Reduce rows and columns by their + * smallest element, compute an initial non-zero dual feasible solution and + * create a greedy matching from workers to jobs of the cost matrix. + */ + reduce(); + computeInitialFeasibleSolution(); + greedyMatch(); + + int w = fetchUnmatchedWorker(); + while (w < dim) { + initializePhase(w); + executePhase(); + w = fetchUnmatchedWorker(); + } + int[] result = Arrays.copyOf(matchJobByWorker, rows); + for (w = 0; w < result.length; w++) { + if (result[w] >= cols) { + result[w] = -1; + } + } + return result; + } + + protected void executePhase() { + while (true) { + int minSlackWorker = -1, minSlackJob = -1; + double minSlackValue = Double.POSITIVE_INFINITY; + for (int j = 0; j < dim; j++) { + if (parentWorkerByCommittedJob[j] == -1) { + if (minSlackValueByJob[j] < minSlackValue) { + minSlackValue = minSlackValueByJob[j]; + minSlackWorker = minSlackWorkerByJob[j]; + minSlackJob = j; + } + } + } + if (minSlackValue > 0) { + updateLabeling(minSlackValue); + } + parentWorkerByCommittedJob[minSlackJob] = minSlackWorker; + if (matchWorkerByJob[minSlackJob] == -1) { + /* + * An augmenting path has been found. + */ + int committedJob = minSlackJob; + int parentWorker = parentWorkerByCommittedJob[committedJob]; + while (true) { + int temp = matchJobByWorker[parentWorker]; + match(parentWorker, committedJob); + committedJob = temp; + if (committedJob == -1) { + break; + } + parentWorker = parentWorkerByCommittedJob[committedJob]; + } + return; + } else { + /* + * Update slack values since we increased the size of the committed + * workers set. + */ + int worker = matchWorkerByJob[minSlackJob]; + committedWorkers[worker] = true; + for (int j = 0; j < dim; j++) { + if (parentWorkerByCommittedJob[j] == -1) { + double slack = costMatrix[worker][j] - labelByWorker[worker] + - labelByJob[j]; + if (minSlackValueByJob[j] > slack) { + minSlackValueByJob[j] = slack; + minSlackWorkerByJob[j] = worker; + } + } + } + } + } + } + + /** + * + * @return the first unmatched worker or {@link #dim} if none. + */ + protected int fetchUnmatchedWorker() { + int w; + for (w = 0; w < dim; w++) { + if (matchJobByWorker[w] == -1) { + break; + } + } + return w; + } + + /** + * Find a valid matching by greedily selecting among zero-cost matchings. This + * is a heuristic to jump-start the augmentation algorithm. + */ + protected void greedyMatch() { + for (int w = 0; w < dim; w++) { + for (int j = 0; j < dim; j++) { + if (matchJobByWorker[w] == -1 && matchWorkerByJob[j] == -1 + && costMatrix[w][j] - labelByWorker[w] - labelByJob[j] == 0) { + match(w, j); + } + } + } + } + + /** + * Initialize the next phase of the algorithm by clearing the committed + * workers and jobs sets and by initializing the slack arrays to the values + * corresponding to the specified root worker. + * + * @param w + * the worker at which to root the next phase. + */ + protected void initializePhase(int w) { + Arrays.fill(committedWorkers, false); + Arrays.fill(parentWorkerByCommittedJob, -1); + committedWorkers[w] = true; + for (int j = 0; j < dim; j++) { + minSlackValueByJob[j] = costMatrix[w][j] - labelByWorker[w] + - labelByJob[j]; + minSlackWorkerByJob[j] = w; + } + } + + /** + * Helper method to record a matching between worker w and job j. + */ + protected void match(int w, int j) { + matchJobByWorker[w] = j; + matchWorkerByJob[j] = w; + } + + /** + * Reduce the cost matrix by subtracting the smallest element of each row from + * all elements of the row as well as the smallest element of each column from + * all elements of the column. Note that an optimal assignment for a reduced + * cost matrix is optimal for the original cost matrix. + */ + protected void reduce() { + for (int w = 0; w < dim; w++) { + double min = Double.POSITIVE_INFINITY; + for (int j = 0; j < dim; j++) { + if (costMatrix[w][j] < min) { + min = costMatrix[w][j]; + } + } + for (int j = 0; j < dim; j++) { + costMatrix[w][j] -= min; + } + } + double[] min = new double[dim]; + for (int j = 0; j < dim; j++) { + min[j] = Double.POSITIVE_INFINITY; + } + for (int w = 0; w < dim; w++) { + for (int j = 0; j < dim; j++) { + if (costMatrix[w][j] < min[j]) { + min[j] = costMatrix[w][j]; + } + } + } + for (int w = 0; w < dim; w++) { + for (int j = 0; j < dim; j++) { + costMatrix[w][j] -= min[j]; + } + } + } + + /** + * Update labels with the specified slack by adding the slack value for + * committed workers and by subtracting the slack value for committed jobs. In + * addition, update the minimum slack values appropriately. + */ + protected void updateLabeling(double slack) { + for (int w = 0; w < dim; w++) { + if (committedWorkers[w]) { + labelByWorker[w] += slack; + } + } + for (int j = 0; j < dim; j++) { + if (parentWorkerByCommittedJob[j] != -1) { + labelByJob[j] -= slack; + } else { + minSlackValueByJob[j] -= slack; + } + } + } +} diff --git a/Algorithms/LCA.java b/Algorithms/LCA.java index 690eb0d..9c7bd86 100755 --- a/Algorithms/LCA.java +++ b/Algorithms/LCA.java @@ -1,148 +1,611 @@ -import java.io.*; -import java.lang.*; +//pakage joney_000[let_me_start] +// import java.util.*; +import java.lang.*; +import java.io.*; import java.math.*; +/* + * Author : joney_000[let_me_start] + * Algorithm : N/A + * Platform : N/A + * + */ + + +/* The Main Class */ +class A +{ + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + /* + Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. + Size Limit : 10^5 + 4 + */ + private final int BUFFER = 5; + private int tempints[] = new int[BUFFER]; + private long templongs[] = new long[BUFFER]; + private double tempdoubles[] = new double[BUFFER]; + private char tempchars[] = new char[BUFFER]; + //private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE / 10; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("output.txt"); + outputStream = new FileOutputStream("output1.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + + } + int MAX_N = 200005; + int n = 0; int m = MAX_N - 1; // tree = (v, e) + int level[] = new int[MAX_N + 1]; // l[v] = level of node v = et[i] + + int et[] = new int[3 * MAX_N + 1]; // euler tour [1..2N] + int f[] = new int[3 * MAX_N + 1]; // f[v] = first occurence of node v in the et + int node[] = new int[6 * MAX_N + MAX_N/100]; // Seg tree size = 3 * (2N) + + LinkedList adj[] = new LinkedList[MAX_N + 1]; //Adjency List + int index = 1; + + void run()throws Exception{ + int tests = i(); + once(); + for(int t = 1; t <= tests; t++){ + clear(); + n = i(); m = n - 1; + for(int i = 1; i <= m; i++){ + int u = i(); int v = i(); + adj[u].add(v); + adj[v].add(u); + } + LinkedList adj1[] = getCopy(adj, n); // wow + dfs(adj1, 1, n); //Assuming that node 1 is the root node + // printEt(et, index); + maketree(1, 1, index, node, level); // index is arround 2 N - 1 but can be greater + // out.write("\n index = "+index+"\n"); + // for(int i = 1; i <= n; i++)out.write(""+f[i]+" "); + // out.write("\n");out.flush(); + // printtree(1, 1, index, node, level); + int q = i(); + for(int qq = 1; qq <= q; qq++){ + int u = i(); int v = i(); + if(f[u] > f[v]){ // who appeared first in et + int x = u; + u = v; + v = x; + } + int lca = et[query(1, 1, index, node, f[u], f[v], level)]; + out.write("lca("+u+", "+v+") = "+lca+"\n"); + } + + } + }// end run + + void once(){ + + } + + void clear(){ + for(int i = 1; i <= MAX_N; i++){ + adj[i] = new LinkedList(); + level[i] = INF; + f[i] = 0; + } + for(int i = 1; i <= 6 * MAX_N + MAX_N/100 - 1; i++){ + node[i] = -1; + } + } + + void printEt(int[] et , int n)throws Exception{ + out.write("\nEuler Tour\n");out.flush(); + for(int i=1; i <= n ;i++){ + out.write(" "+ et[i]); + } + out.flush(); + } + + // Maintain mutability + LinkedList[] getCopy(LinkedList adj[], int n)throws Exception{ + LinkedList adj_copy[] = new LinkedList[n + 1]; + for(int i = 1; i <= n; i++){ + adj_copy[i] = new LinkedList(); + for(int x: adj[i]){ + adj_copy[i].add(x); + } + } + return adj_copy; + } + + void dfs(LinkedList adj[], int root, int n)throws Exception{ + + boolean vis[] = new boolean[n+1]; + LinkedList q = new LinkedList(); + index = 1; + int l = 0; //level + + q.add(root); + vis[root] = true; + + while(!q.isEmpty()){ + + int u = q.getLast(); // The Stack + level[u] = l; + if(f[u] == 0)f[u] = index; // setting first occurence + + if(et[index-1] != u){ // IMP : if it's not leaf node + et[index] = u; + index++; + } + + if(adj[u].size()>0){ + int v = adj[u].removeFirst(); + if(!vis[v]){ + q.add(v); + l++; + vis[v] = true; + level[v] = l; + et[index] = v; + if(f[v] == 0)f[v] = index; // setting first occurence + index++; + } -class LCA { - public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in),2000); - public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out),2000); - - public static void main(String[] args)throws Exception{ - - - - - String[] s = br.readLine().split(" "); - int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); - int et[] = new int[2*n]; //euler tour [1..2n-1] - LinkedList adj[] = new LinkedList[n+1]; //Adjency List - for(int i=1;i<=n ;i++)adj[i]=new LinkedList(); //init List - int l[] = new int[2*n]; //l[i] = level of node et[i] - int f[] = new int[n+1]; //f[i] = first occurence of node i in the et - - int node[] = new int[4*(2*n)]; //seg tree - int level[] = new int[n+1]; // level[i]= level of node i in the tree - int u=0,v=0; - for(int i=1;i<=m;i++){ - - s = br.readLine().split(" "); - u=Integer.parseInt(s[0]); - v=Integer.parseInt(s[1]); - adj[u].add(v); - - } - dfs(adj,1,level,et,n); //Assuming that node 1 is the root node - printEt(et,n); - printNodeLevels(level,n); - - for(int i=1;i<=2*n-1;i++){ - l[i]=level[et[i]]; - if(f[et[i]]==0)f[et[i]]=i; - - } - - maketree(1,1,2*n-1,node,l); //l[1..2*n-1] - out.write("\nTree Built\n");out.flush(); - //for(int i=1;i<=n;i++)out.write(" "+f[i]); - //out.flush(); - printtree(1,1,2*n-1,node,l); - int q = Integer.parseInt(br.readLine()); - int temp=0,ans=0; - for(int i=1;i<=q;i++){ - - s = br.readLine().split(" "); - u = Integer.parseInt(s[0]); v = Integer.parseInt(s[1]); - if(f[u]>=f[v]){ //swap u,v - temp = u; u=v; v=temp; - } - out.write("indexes i="+f[u]+" j="+f[v]);out.flush(); - ans = et[query(1,1,2*n-1,node,l,f[u],f[v])]; - out.write(""+ans+"\n");out.flush(); - } - out.flush(); - - - } - public static void printtree(int index,int i,int j,int[] node,int []L)throws Exception{ - if(i==j){out.write("\n min value btwn i="+i+" j="+j+" is"+node[index]);out.flush(); - return;} - - printtree(2*index,i,(i+j)/2,node,L); - printtree(2*index+1,((i+j)/2)+1,j,node,L); - out.write("\n min value btwn i="+i+" j="+j+" is"+node[index]);out.flush(); - - } - public static void maketree(int index,int i,int j,int[] node,int []L)throws Exception{ - if(i==j){node[index]=i; return; } - - maketree(2*index,i,(i+j)/2,node,L); - maketree(2*index+1,((i+j)/2)+1,j,node,L); - - if(L[node[2*index]]<=L[node[2*index+1]])node[index]=node[2*index]; - else node[index]=node[2*index+1]; - } - public static int query(int index,int l,int r,int[] node,int []L,int i,int j)throws Exception{ - if(l>j||rr)return -1; //invalid condition - if(l>=i&&r<=j) return node[index]; - - int p1 = query(2*index,l,(l+r)/2,node,L,i,j); - int p2 = query(2*index+1,((l+r)/2)+1,r,node,L,i,j); - - if(p1==-1)return p2; - if(p2==-1)return p1; - if(L[p1]<=L[p2])return p1; - else return p2; - } - - public static void printEt(int[] et , int n)throws Exception{ - out.write("Euler Tour\n");out.flush(); - for(int i=1; i<=2*n-1 ;i++){ - out.write(" "+et[i]); - - } - out.flush(); - } - public static void printNodeLevels(int[] level , int n)throws Exception{ - out.write("levels\n");out.flush(); - for(int i=1; i<=n ;i++){ - out.write(" node "+i+" ="+level[i]); - - } - out.flush(); - } - public static void dfs(LinkedList adj[] ,int root, int level[] ,int et[] , int n)throws Exception{ - - boolean visited[] = new boolean[n+1]; - LinkedList q = new LinkedList(); - int index = 1; - int l = 0;//level - - q.add(root); - visited[root]=true; - - while(!q.isEmpty()){ - - int u = q.getLast(); //top - if(et[index-1]!=u){et[index]=u;index++;}//if it's not leaf node - level[u]=l; - - if(adj[u].size()>0){ - int v = adj[u].removeFirst(); - if(!visited[v]){ - q.add(v);l++; - visited[v]=true; level[v]=l; - et[index]=v; index++; - } - - }else{ - - int v = q.removeLast(); - l--; - - } - - } - } + }else { + int v = q.removeLast(); + l--; + } + + } + --index; // et[1..index] + } + void printtree(int idx,int i,int j,int[] node,int []L)throws Exception{ + if(i==j){ + out.write("\n node value btwn i ="+i+" j="+j+" is"+node[idx]);out.flush(); + return; + } + + printtree(2*idx, i, (i+j)/2, node, L); + printtree(2*idx+1, ((i+j)/2)+1, j, node, L); + out.write("\n node value btwn i ="+i+" j="+j+" is"+node[idx]);out.flush(); + + } + + void maketree(int idx, int i, int j, int[] node, int []L)throws Exception{ + if(i==j){ + node[idx] = i; // node holds the et index + return; + } + + maketree(2 * idx, i, (i+j)/2, node, L); + maketree(2 * idx + 1, ((i+j)/2)+1, j, node, L); + + if(L[et[node[2*idx]]] <= L[et[node[2*idx + 1]]])node[idx] = node[2 * idx]; + else node[idx] = node[2*idx + 1]; + } + + int query(int idx, int l, int r, int[] node, int i, int j, int []L)throws Exception{ + if(l>j||rr)return -1; //invalid condition + if(l>=i && r<=j) return node[idx]; + + int p1 = query(2*idx, l, (l+r)/2, node, i, j, L); + int p2 = query(2*idx+1, ((l+r)/2)+1, r, node, i, j, L); + + if(p1==-1)return p2; + if(p2==-1)return p1; + if(L[et[p1]] <= L[et[p2]])return p1; + else return p2; + } + //****************************** Gerenal Utilities ***********************// + void print_r(Object... o){ + out.write("\n"+Arrays.deepToString(o)+"\n"); + out.flush(); + } + + boolean isPrime(long n){ + if(n==1)return false; + if(n<=3)return true; + if(n%2==0)return false; + for(int i=2 ;i <= Math.sqrt(n); i++){ + if(n%i==0)return false; + } + return true; + } + // sieve + int[] primes(int n){ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); + boolean arr[] = new boolean[n+1]; + Arrays.fill(arr,true); + arr[1]=false; + for(int i=2;i<=Math.sqrt(n);i++){ + if(!arr[i])continue; + for(int j = 2*i ;j<=n;j+=i){ + arr[j]=false; + } + } + LinkedList ll = new LinkedList(); + for(int i=1;i<=n;i++){ + if(arr[i])ll.add(i); + } + n = ll.size(); + + int primes[] = new int[n+1]; + for(int i=1;i<=n;i++){ + primes[i]=ll.removeFirst(); + } + return primes; +} +long gcd(long a , long b){ + if(b==0)return a; + return gcd(b , a%b); } - +long lcm(long a , long b){ + if(a==0||b==0)return 0; + return (a*b)/gcd(a,b); +} +long mulmod(long a , long b ,long mod){ + if(a==0||b==0)return 0; + if(b==1)return a; + long ans = mulmod(a,b/2,mod); + ans = (ans*2)% mod; + if(b%2==1)ans = (a + ans)% mod; + return ans; +} +long pow(long a , long b ,long mod){ + if(b==0)return 1; + if(b==1)return a; + long ans = pow(a,b/2,mod); + ans = (ans * ans); + if(ans >= mod )ans %= mod; + + if(b%2==1)ans = (a * ans); + if(ans >= mod )ans %= mod; + + return ans; +} + // 20*20 nCr Pascal Table +long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} + for(int j=0;j<=20 ;j++){ + for(int i=j+1;i<= 20 ;i++){ + ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; + } + } + return ncr; + } + //*******************************I/O******************************// + int i()throws Exception{ + //return Integer.parseInt(br.readLine().trim()); + return in.nextInt(); + } + int[] is(int n)throws Exception{ + //int arr[] = new int[n+1]; + for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); + return tempints; + } + long l()throws Exception{ + return in.nextLong(); + } + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); + return templongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); + return tempdoubles; + } + char c()throws Exception{ + return in.nextCharacter(); + } + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); + return tempchars; + } + String s()throws Exception{ + return in.nextLine(); + } + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } +//***********************I/O ENDS ***********************// +//*********************** 0.3%f [precision]***********************// +/* roundoff upto 2 digits + double roundOff = Math.round(a * 100.0) / 100.0; + or + System.out.printf("%.2f", val); + +*/ +/* + print upto 2 digits after decimal + val = ((long)(val * 100.0))/100.0; + +*/ + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + public static void main(String[] args) throws java.lang.Exception{ + //let_me_start Shinch Returns + + + /* + // Old Reader Writer + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); + BufferedReader br=new BufferedReader(new FileReader("input.txt")); + BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); + */ + A driver = new A(true); + + driver.run(); + + driver.closeResources(); + return ; + + } + + } + + class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } + } + /******************** Pair class ***********************/ + + class Pair implements Comparable{ + public int a; + public int b; + public int c; + public Pair(){ + this.a = 0; + this.b = 0; + } + public Pair(int a,int b, int c){ + this.a = a; + this.b = b; + this.c = c; + } + public int compareTo(Pair p){ + if(this.a==p.a){ + return this.b-p.b; + } + return p.a-this.a; + } + public String toString(){ + return "a="+this.a+" b="+this.b; + } + +} diff --git a/Algorithms/MergeSort.java b/Algorithms/MergeSort.java index 46fad14..6f8da29 100755 --- a/Algorithms/MergeSort.java +++ b/Algorithms/MergeSort.java @@ -1,58 +1,495 @@ -/* package joney_000 */ - +//pakage joney_000[let_me_start] +// import java.util.*; import java.lang.*; import java.io.*; import java.math.*; +/* + * Author : joney_000[let_me_start] + * Algorithm : Merge Sort + * Platform : HackerRank + * + */ + +/* The Main Class */ +class A +{ + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + /* + Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases. + Size Limit : 10^5 + 4 + */ + private final int BUFFER = 50000; + private int tempints[] = new int[BUFFER]; + private long templongs[] = new long[BUFFER]; + private double tempdoubles[] = new double[BUFFER]; + private char tempchars[] = new char[BUFFER]; + //private final long mod = 1000000000+7; + private final int INF = Integer.MAX_VALUE / 10; + private final long INF_L = Long.MAX_VALUE / 10; -class Main + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("output.txt"); + outputStream = new FileOutputStream("output1.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + + } + int MAX_N = 1000005; + int n = 0; + int a[] = new int[MAX_N]; - { - - public static void main(String[] args)throws Exception{ + void run()throws Exception{ + // int tests = i(); + // for(int t = 1; t <= tests; t++){ + // clear(); + n = i(); + for(int i = 1; i <= n; i++)a[i] = i(); + mergeSort(a, 1, n); + for(int i = 1; i <= n; i++)out.write(""+a[i]+" "); + //out.write(""+ans+"\n"); + // } + }// end run + + void mergeSort(int a[], int st, int end){ + if(st >= end)return; + int mid = st + (end - st)/2; + mergeSort(a, st, mid); + mergeSort(a, mid + 1, end); + merge(a, st, end); + } - BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); - int n = Integer.parseInt(br.readLine()); - int arr [] = new int[100005]; - String[] s = br.readLine().split(" "); - for(int i=1;i<=n;i++)arr[i]=Integer.parseInt(s[i-1]); - mergeSort(arr,1,n); - for(int i=1;i<=n;i++)out.write(""+arr[i]+" "); - out.flush(); - + void merge(int[] a, int st, int end){ + LinkedList sortedList = new LinkedList(); + int mid = st + (end - st)/2; + int p1 = st; int p2 = mid + 1; + while(p1 <= mid && p2 <= end){ + if(a[p1] <= a[p2])sortedList.add(a[p1++]); + else sortedList.add(a[p2++]); + } + while(p1 <= mid)sortedList.add(a[p1++]); + while(p2 <= end)sortedList.add(a[p2++]); + p1 = st; + while(!sortedList.isEmpty())a[p1++] = (Integer)sortedList.removeFirst(); } - public static void mergeSort(int arr[],int st ,int end)throws Exception{ + + void clear(){ - if(st>=end)return; - int mid = (st+end)/2; ////Same as mid=l+(r-l)/2;, but this avoids integer overflow for large l and h - mergeSort(arr,st,mid); - mergeSort(arr,mid+1,end); - merge(arr,st,mid,end); - } + + //****************************** Gerenal Utilities ***********************// + + void print_r(Object... o){ + out.write("\n"+Arrays.deepToString(o)+"\n"); + out.flush(); + } + + boolean isPrime(long n){ + if(n==1)return false; + if(n<=3)return true; + if(n%2==0)return false; + for(int i=2 ;i <= Math.sqrt(n); i++){ + if(n%i==0)return false; + } + return true; + } + // sieve + int[] primes(int n){ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" "); + boolean arr[] = new boolean[n+1]; + Arrays.fill(arr,true); + arr[1]=false; + for(int i=2;i<=Math.sqrt(n);i++){ + if(!arr[i])continue; + for(int j = 2*i ;j<=n;j+=i){ + arr[j]=false; + } + } + LinkedList ll = new LinkedList(); + for(int i=1;i<=n;i++){ + if(arr[i])ll.add(i); + } + n = ll.size(); - public static void merge(int arr[],int st ,int mid, int end)throws Exception{ - - LinkedList L = new LinkedList(); - LinkedList R = new LinkedList(); - - for(int i=st;i<=mid;i++)L.add(arr[i]); - for(int i=mid+1;i<=end;i++)R.add(arr[i]); - while((!L.isEmpty())&&(!R.isEmpty())){ - int a = L.getFirst(); - int b = R.getFirst(); - if(a<=b){ - arr[st]=L.removeFirst(); - st++; - }else{ - arr[st]=R.removeFirst(); - st++; - } - } - while(!L.isEmpty()){arr[st]=L.removeFirst();st++;} - while(!R.isEmpty()){arr[st]=R.removeFirst();st++;} - } - - } + int primes[] = new int[n+1]; + for(int i=1;i<=n;i++){ + primes[i]=ll.removeFirst(); + } + return primes; +} +long gcd(long a , long b){ + if(b==0)return a; + return gcd(b , a%b); +} +long lcm(long a , long b){ + if(a==0||b==0)return 0; + return (a*b)/gcd(a,b); +} +long mulmod(long a , long b ,long mod){ + if(a==0||b==0)return 0; + if(b==1)return a; + long ans = mulmod(a,b/2,mod); + ans = (ans*2)% mod; + if(b%2==1)ans = (a + ans)% mod; + return ans; +} +long pow(long a , long b ,long mod){ + if(b==0)return 1; + if(b==1)return a; + long ans = pow(a,b/2,mod); + ans = (ans * ans); + if(ans >= mod )ans %= mod; + + if(b%2==1)ans = (a * ans); + if(ans >= mod )ans %= mod; + + return ans; +} + // 20*20 nCr Pascal Table +long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;} + for(int j=0;j<=20 ;j++){ + for(int i=j+1;i<= 20 ;i++){ + ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1]; + } + } + return ncr; + } + //*******************************I/O******************************// + int i()throws Exception{ + //return Integer.parseInt(br.readLine().trim()); + return in.nextInt(); + } + int[] is(int n)throws Exception{ + //int arr[] = new int[n+1]; + for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt(); + return tempints; + } + long l()throws Exception{ + return in.nextLong(); + } + long[] ls(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong(); + return templongs; + } + + double d()throws Exception{ + return in.nextDouble(); + } + double[] ds(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble(); + return tempdoubles; + } + char c()throws Exception{ + return in.nextCharacter(); + } + char[] cs(int n)throws Exception{ + for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter(); + return tempchars; + } + String s()throws Exception{ + return in.nextLine(); + } + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } +//***********************I/O ENDS ***********************// +//*********************** 0.3%f [precision]***********************// +/* roundoff upto 2 digits + double roundOff = Math.round(a * 100.0) / 100.0; + or + System.out.printf("%.2f", val); + +*/ +/* + print upto 2 digits after decimal + val = ((long)(val * 100.0))/100.0; + +*/ + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + public static void main(String[] args) throws java.lang.Exception{ + //let_me_start Shinch Returns + + + /* + // Old Reader Writer + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); + BufferedReader br=new BufferedReader(new FileReader("input.txt")); + BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); + */ + A driver = new A(true); + + driver.run(); + + driver.closeResources(); + return ; + + } + + } + + class FastReader{ + + private boolean finished = false; + + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } + } + /******************** Pair class ***********************/ + + class Pair implements Comparable{ + public int a; + public int b; + public int c; + public Pair(){ + this.a = 0; + this.b = 0; + } + public Pair(int a,int b, int c){ + this.a = a; + this.b = b; + this.c = c; + } + public int compareTo(Pair p){ + if(this.a==p.a){ + return this.b-p.b; + } + return p.a-this.a; + } + public String toString(){ + return "a="+this.a+" b="+this.b; + } + +} diff --git a/Algorithms/MillerRabin.java b/Algorithms/MillerRabin.java new file mode 100644 index 0000000..a808942 --- /dev/null +++ b/Algorithms/MillerRabin.java @@ -0,0 +1,56 @@ +/** + * Author : joney_000 [developer.jaswant@gmail.com] + * Algorithm : Miller Rabin + * Platform : Codejam + * Ref : https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Testing_against_small_sets_of_bases + */ + +class MillerRabin { + + /* @input: `number` for which we need to check weather it is prime or not + * @description: this is the deterministic varient of the miller ribbin + */ + boolean isPrime(long number){ + if(number < 2){ + return false; + } + int smallPrimes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + for(int prime : smallPrimes){ + if(number % prime == 0){ + return number == prime; + } + } + int trailingZeros = Long.numberOfTrailingZeros(number - 1); + long power = (number - 1) >> trailingZeros; + long bases[] = {2, 7, 61}; + // sufficient for number < 4,759,123,141 + // we dont need to test all the base a < 2(ln number)2 + for(long base: bases){ + long exp = pow(base % number, power, number); + if(exp <= 1 || exp == number - 1){ + continue; + } + for(int i = 0; i < trailingZeros - 1 && exp != number - 1; i++){ + exp = (exp * exp) % number; // warning: integer overflow, use mulMod in case of int\long overflow + } + if(exp != number - 1){ + return false; + } + } + return true; + } + + long pow(long a, long b, long mod){ + if(b == 0) + return 1; + if(b == 1) + return a % mod; + long ans = pow(a, b/2, mod); + ans = (ans * ans) % mod; + // mulMod(ans, ans, mod); use when ans^2 does int or long overflow. + // this will perform multiplication using divide and conquer + if(b % 2 == 1) + ans = (a * ans) % mod; // warning: integer overflow + return ans; + } +} \ No newline at end of file diff --git a/Algorithms/Multiset.java b/Algorithms/Multiset.java new file mode 100644 index 0000000..a1b0cd0 --- /dev/null +++ b/Algorithms/Multiset.java @@ -0,0 +1,47 @@ +import java.util.HashMap; + +/* @author: jaswant developer.jaswant@gmail.com + * @algorithm: hashing + * @use: holding frequency map, similar to multiset in c++ +*/ +class MultiSet { + + private HashMap multiSet = new HashMap(); + private int size; + + public int get(K key){ + return multiSet.getOrDefault(key, 0); + } + + public void add(K key){ + size++; + multiSet.put(key, get(key)+ 1); + } + + public void remove(K key){ + int freq = get(key); + size--; + if(freq == 1){ + multiSet.remove(key); + }else{ + multiSet.put(key, freq - 1); + } + } + + public int size(){ + return size; + } + + public boolean isEmpty(){ + return size == 0; + } + + public boolean containsKey(K key){ + return multiSet.containsKey(key); + } + + @Override + public String toString(){ + return multiSet.toString(); + } +} diff --git a/Algorithms/NumberTheoreticTransform.java b/Algorithms/NumberTheoreticTransform.java new file mode 100644 index 0000000..d538956 --- /dev/null +++ b/Algorithms/NumberTheoreticTransform.java @@ -0,0 +1,564 @@ +import java.util.Vector; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.LinkedList; + +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.OutputStream; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.PrintWriter; + +import java.util.InputMismatchException; + +import java.io.IOException; +import java.io.FileNotFoundException; + +import java.lang.Math; +import java.math.BigInteger; +/* + * Author : joney_000[Jaswant Singh][E-mail: developer.jaswant@gmail.com] + * Algorithm : NTT- Number Theoretic Transform, Polynomial Multiplication Time: O(N log N) Space: O(N) , + * N = polynomial order woth given mod of the form mod = p * q + 1 p,q > 0 + * Platform : Codeforces + * Ref : https://codeforces.com/blog/entry/43499 + * https://gist.github.com/meooow25/0d61a01c0621efde7a83e1ef1dce898d +**/ + +class A { + + private InputStream inputStream ; + private OutputStream outputStream ; + private FastReader in ; + private PrintWriter out ; + + + private final long mod = 998244353; + private final int INF = Integer.MAX_VALUE; + private final long INF_L = Long.MAX_VALUE / 10; + + public A(){} + public A(boolean stdIO)throws FileNotFoundException{ + // stdIO = false; + if(stdIO){ + inputStream = System.in; + outputStream = System.out; + }else{ + inputStream = new FileInputStream("input.txt"); + outputStream = new FileOutputStream("output.txt"); + } + in = new FastReader(inputStream); + out = new PrintWriter(outputStream); + } + + final int MAX_N = 1 << 15; + + void run()throws Exception{ + int n = i(); int m = i(); + long a[] = new long[n]; + long b[] = new long[n]; + + for(int i = 1; i <= n; i++)a[i] = l(); + for(int i = 1; i <= n; i++)a[i] = l(); + // NumberTheoryTransform.findSmallestPrimitiveRoot(mod); + + long res[] = NumberTheoryTransform.multiply(a, b); + + // out.flush(); + + } + + void clear(){ + + } + + long gcd(long a, long b){ + if(b == 0)return a; + return gcd(b, a % b); + } + + long lcm(long a, long b){ + if(a == 0 || b == 0)return 0; + return (a * b)/gcd(a, b); + } + + long mulMod(long a, long b, long mod){ + if(a == 0 || b == 0)return 0; + if(b == 1)return a; + long ans = mulMod(a, b/2, mod); + ans = (ans * 2) % mod; + if(b % 2 == 1)ans = (a + ans)% mod; + return ans; + } + + long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + return ans; + } + // 20*20 nCr Pascal Table + long[][] ncrTable(){ + long ncr[][] = new long[21][21]; + for(int i = 0; i <= 20; i++){ + ncr[i][0] = ncr[i][i] = 1L; + } + for(int j = 0; j <= 20; j++){ + for(int i = j + 1; i <= 20; i++){ + ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; + } + } + return ncr; + } + + int i()throws Exception{ + return in.nextInt(); + } + + long l()throws Exception{ + return in.nextLong(); + } + + double d()throws Exception{ + return in.nextDouble(); + } + + char c()throws Exception{ + return in.nextCharacter(); + } + + String s()throws Exception{ + return in.nextLine(); + } + + BigInteger bi()throws Exception{ + return in.nextBigInteger(); + } + + private void closeResources(){ + out.flush(); + out.close(); + return; + } + + public static void main(String[] args) throws java.lang.Exception{ + A driver = new A(true); + driver.run(); + driver.closeResources(); + } +} + +class FastReader{ + + private boolean finished = false; + private InputStream stream; + private byte[] buf = new byte[4 * 1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + + public FastReader(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 peek(){ + if (numChars == -1){ + return -1; + } + if (curChar >= numChars){ + curChar = 0; + try{ + numChars = stream.read (buf); + } catch (IOException e){ + return -1; + } + if (numChars <= 0){ + return -1; + } + } + return buf[curChar]; + } + + public int nextInt(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + int res = 0; + do{ + if(c==','){ + c = read(); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public long nextLong(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + long res = 0; + do{ + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } while (!isSpaceChar (c)); + return res * sgn; + } + + public String nextString(){ + 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; + } + + private String readLine0(){ + StringBuilder buf = new StringBuilder (); + int c = read (); + while (c != '\n' && c != -1){ + if (c != '\r'){ + buf.appendCodePoint (c); + } + c = read (); + } + return buf.toString (); + } + + public String nextLine(){ + String s = readLine0 (); + while (s.trim ().length () == 0) + s = readLine0 (); + return s; + } + + public String nextLine(boolean ignoreEmptyLines){ + if (ignoreEmptyLines){ + return nextLine (); + }else{ + return readLine0 (); + } + } + + public BigInteger nextBigInteger(){ + try{ + return new BigInteger (nextString ()); + } catch (NumberFormatException e){ + throw new InputMismatchException (); + } + } + + public char nextCharacter(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + return (char) c; + } + + public double nextDouble(){ + int c = read (); + while (isSpaceChar (c)) + c = read (); + int sgn = 1; + if (c == '-'){ + sgn = -1; + c = read (); + } + double res = 0; + while (!isSpaceChar (c) && c != '.'){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + res *= 10; + res += c - '0'; + c = read (); + } + if (c == '.'){ + c = read (); + double m = 1; + while (!isSpaceChar (c)){ + if (c == 'e' || c == 'E'){ + return res * Math.pow (10, nextInt ()); + } + if (c < '0' || c > '9'){ + throw new InputMismatchException (); + } + m /= 10; + res += (c - '0') * m; + c = read (); + } + } + return res * sgn; + } + + public boolean isExhausted(){ + int value; + while (isSpaceChar (value = peek ()) && value != -1) + read (); + return value == -1; + } + + public String next(){ + return nextString (); + } + + public SpaceCharFilter getFilter(){ + return filter; + } + + public void setFilter(SpaceCharFilter filter){ + this.filter = filter; + } + + public interface SpaceCharFilter{ + public boolean isSpaceChar(int ch); + } +} + +class Pair implements Comparable{ + public int idx; + public int a; + public int b; + + public Pair(){ + this.a = 0; + this.b = 0; + } + + public Pair(int _idx, int a, int b){ + this.a = a; + this.b = b; + this.idx = _idx; + } + + public int compareTo(Pair p){ + if(this.a == p.a){ + return this.b - p.b; + } + return this.a - p.a; + } + + @Override + public String toString(){ + return "a = " + this.a + " b = " + this.b; + } +} + +class NumberTheoryTransform { + + private static long mod = 998244353; + private static long primitiveRoot = 3; // w = omega = a = primitive_root + private static long primitiveRootInverse = 332748118; + private static final int MAX_N = 1 << 15; + private static long A[] = new long[MAX_N]; + private static long B[] = new long[MAX_N]; + + static void findSmallestPrimitiveRoot(long primeNo){ + int sz = (int)Math.sqrt(primeNo) + 1; + boolean isPrime[] = new boolean[sz + 1]; + Arrays.fill(isPrime, 2, sz + 1, true); + for(int i = 2; i <= sz; i++){ + if(isPrime[i]){ + for(int j = i + i; j <= sz; j += i){ + isPrime[j] = false; + } + } + } + + long val = primeNo - 1; + ArrayList primtFactors = new ArrayList(); + for(int i = 2; i <= sz; i++){ + if(isPrime[i]){ + if(val % i == 0)primtFactors.add(i); + while(val % i == 0)val /= i; + } + } + if(val > 1)primtFactors.add((int)val); + // System.out.print("printFactors: "+primtFactors+"\n"); + for(primitiveRoot = 2; primitiveRoot <= primeNo - 1; primitiveRoot++){ // try every number + boolean check = true; + for(int x: primtFactors){ // divisors of primeNo - 1 + if(pow(primitiveRoot, (primeNo - 1)/x, primeNo) == 1){ + check = false; + break; + } + } + if(check)break; + } + System.out.print("primitive_root("+mod+") or w = "+ primitiveRoot +"\n"); + primitiveRootInverse = pow(primitiveRoot, primeNo - 2, primeNo); + System.out.print("inverse of w(omega) = "+ primitiveRootInverse +"\n"); + } + + static long pow(long a, long b, long mod){ + if(b == 0)return 1; + if(b == 1)return a; + long ans = pow(a, b/2, mod); + ans = (ans * ans); + if(ans >= mod)ans %= mod; + if(b % 2 == 1)ans = (a * ans); + if(ans >= mod)ans %= mod; + return ans; + } + + static void ntt_inplace(long[] a, int n, boolean invert) { + + for(int i = 0; i < n; ++i){ + int j = 0; + int x = i, y = n - 1; + while(y > 0) { + j = (j << 1) + (x & 1); + x >>= 1; + y >>= 1; + } + if(i < j){ + long temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + + for (int len = 2; len <= n; len <<= 1) { + long root = invert ? pow(primitiveRootInverse, (mod - 1)/len, mod) : pow(primitiveRoot, (mod - 1)/len, mod); + for (int i = 0; i < n; i += len) { + long w = 1L; + for (int j = 0; j < len / 2; j++) { + long u = a[i + j], v = (a[i + j + len/2] * w) % mod; + a[i+j] = u + v < mod ? u + v : u + v - mod; + a[i + j + len/2] = u - v >= 0 ? u - v : u - v + mod; + w = (w * root) % mod; + } + } + } + + if(invert){ + long invN = pow(n, mod - 2, mod); // 1/n % p + for (int i = 0; i < n; ++i)a[i] = (a[i] * invN) % mod; // c[i] = c[i] / n % mod + } + } + + static long[] multiply(long[] a, long[] b) { + int resultSize = Integer.highestOneBit(Math.max(a.length, b.length) - 1) << 2; + resultSize = Math.max(resultSize, 1); + long[] C = new long[resultSize]; + + for(int i = 0; i < a.length; i++)A[i] = a[i]; + for(int i = 0; i < b.length; i++)B[i] = b[i]; + for(int i = a.length; i < resultSize; i++)A[i] = 0; + for(int i = b.length; i < resultSize; i++)B[i] = 0; + + // if(resultSize <= 20){ + // naiveMultiply(A, B, C, resultSize); + // return C; + // } + + ntt_inplace(A, resultSize, false); + ntt_inplace(B, resultSize, false); + for (int i = 0; i < resultSize; ++i){C[i] = A[i] * B[i]; if(C[i] >= mod)C[i] %= mod;} // Linear convolution + ntt_inplace(C, resultSize, true); + return C; + } + + static void naiveMultiply(long a[], long b[], long c[],int n){ + for(int i = 0 ; i< n ; i++) c[i]=0 ; + for(int i = 0 ; i < n ; i++){ + for(int j = 0 ; j < n ; j++){ + if(i + j >= n) continue; + c[i + j] += a[i] * b[j]; + if(c[i + j] >= mod)c[i + j] %= mod ; + } + } + } + + static long[] polynomialPow(long[] b, int pow){ + long a[] = new long[b.length]; + a[0] = 1; + int k = pow; + while(k > 0){ + if(k % 2 == 1) + a = multiply(a, b); + b = multiply(b, b); + k /= 2; + } + return a; + } + + static long[] polynomialPowBrute(long[] b, int pow){ + pow += 2; + long a[] = new long[b.length]; + a[0] = 1; + for(int i = 1; i <= pow; i++){ + System.out.print("at pow "+i+"\n"); + System.out.println(""); + a = multiply(a, b); + for(int x = 0; x < Math.min(a.length, 40); x++){ + if(a[x] != 0){ + System.out.print(""+x+" "); + } + } + System.out.flush(); + } + return a; + } +} diff --git a/Algorithms/PersistantTrie-Immutable-DS.java b/Algorithms/PersistantTrie-Immutable-DS.java new file mode 100644 index 0000000..a132cea --- /dev/null +++ b/Algorithms/PersistantTrie-Immutable-DS.java @@ -0,0 +1,674 @@ +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.*; + +/** +* @Auther : Jaswant Singh [jaswant.singh@practo.com, jaswantsinghyadav007@gmail.com] +* @Date : Tue Jun 6 23:08:33 IST 2017 +* @Algorithm: Persistent Data Structure : Persistent Trie Implementation/ IMMUTABLE DATA STRUCTURE +*