q.add(start);
visited[start] = true;
while (!q.isEmpty()) {
int temp = q.remove();
for (int i = 0; i < graph.get(temp).size(); i++) {
if (!visited[i]) {
visited[i] = true;
q.add(i);
}
}
}
public static void dfs(ArrayList<ArrayList<Integer>> graph,int start){
q.add(start);
visited[start] = true;
while(!s.isEmpty()){
int temp=s.pop();
ArrayList<Integer> neighbours=graph.get(temp);
for(int n:neighbours){
if(!visited[n]){
s.add(n);
visited[n]=true;
}
}
}
}
public static int dijkstras(Vertex[] graph, int source, int destination) {
boolean[] visited =new boolean[graph.length];
Vertex current = graph[source];
PriorityQueue<Vertex> pq = new PriorityQueue<Vertex>();
//intially minDistance for each vertex would be Integer.MAXVALUE make start distance as zero
current.minDistance=0;
pq.add(current);
while (!pq.isEmpty()) {
current = pq.remove();
if (current.id == destination) {
break;
}
if(visited[current.id]){
continue;
}else{
visited[current.id]=true;
}
//updating all the unvisited new neighbour values and insert in pq
for (Edge e : current.neighbors) {
if((visited[e.end])){continue;}
Vertex end = graph[e.end];
int distance = e.distance;
int newMin = distance + current.minDistance;
if (newMin < end.minDistance ) {
end.minDistance = newMin;
pq.add(end);
}
}
}
return graph[destination].minDistance;
}
private static int PrimsAlgorithm(Vertex[] graph, int source) {
PriorityQueue<Edge> pq=new PriorityQueue<Edge>();
boolean[] visited=new boolean[graph.length];
int cost=0;
visited[source]=true;
for(Edge e:graph[source].neighbors){
pq.add(e);
}
while(!pq.isEmpty()){
Edge current=pq.remove();
if(visited[current.edge]){
continue;
}
visited[current.edge]=true;
cost=cost+current.cost;
//adding all the unvisited neoghbours into the priority pq
for(Edge e:graph[current.edge].neighbors){
if(visited[e.edge]){
continue;
}
pq.add(e);
}
}
return cost;
}
comparable on the cost of edge and put it pq and add the edges into MST when only it results in union of two different sets.
taking care of disjoint sets:
public static class DisjointSets {
int[] parents;
public DisjointSets(int size) {
parents = new int[size];
for (int i = 0; i < size; i++) {
parents[i] = i;
}
}
public int find(int x) {
if (parents[x] == x) {
return x;
}else{
parents[x]=find(parents[x]);
return parents[x];
}
}
public void union(int x,int y){
parents[find(x)]=find(y);
}
}
add all the edges to pq and send it as parameter for function
private static int kruskals(PriorityQueue<Edge> pq, int v) {
DisjointSets ds=new DisjointSets(v);
Edge current;
int components=v;
int cost=0;
while(!pq.isEmpty()){
current=pq.remove();
if(ds.find(current.edge)==ds.find(current.oEdge)){
continue;
}
components--;
ds.union(current.edge,current.oEdge);
cost+=current.cost;
}
if(components>1){
return -1;
}else{
return cost;
}
}
description: on arrays to find the position of an element with the minimum value between two specified indices.
Algo: preprocess sqrt(N) segment minimums range given then 2 half participated and remaining all full participated segments.
when update(i,X) then calculate min for inserted segment O(sqrt(N))
desc : can be reduced to a restricted version of an RMQ problem, in which consecutive array elements differ by exactly 1.
preprocessing:O(N) divide into sqrt(h) height segments make each element in the segment point to the least ancestor in the next height segment. query:O(log(N)) lca(a,b) then check the height segment of the nodes and make min of them jump segmnts till it reaches the the other by moving up to its parents similar to previous problem then
if both parent for next height segment values are same then start moving up the in the same height segment one after another by comparing both of their parents else move both pointers to next height segment to their resoectice parents
other algo : write inorder of the tree and find minimum in range of tree index [a,b] .
try coding it
struct Node *findLCA(struct Node* root, int n1, int n2)
{
if (root == NULL) return NULL;
if (root->key == n1 || root->key == n2)
return root;
Node *left_lca = findLCA(root->left, n1, n2);
Node *right_lca = findLCA(root->right, n1, n2);
if (left_lca && right_lca) return root;
return (left_lca != NULL)? left_lca: right_lca;
}
problems: http://www.spoj.com/problems/LCASQ/ http://www.spoj.com/problems/RMQSQ/ http://www.spoj.com/problems/LCA/
a[] =original array b[] =cumative sum array
get an array which have sum of all the b[i]=b[i-1]+a[i]
can be done better by using: Fenwick tree or binary indexed tree
least significant bit of x = x & -x
-x = !x + 1
class BIT {
int[] tree;
public BIT(int n) {
this.tree = new int[n];
}
int lsb(int x) {
return x & -x;
}
void update(int i, int x) {
while (i <= tree.length-1) {
tree[i] += x;
i += lsb(i);
}
}
int query(int i) {
int sum = 0;
while (i > 0) {
sum += tree[i];
i -= lsb(i);
}
return sum;
}
}
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees http://pdf.aminer.org/001/073/976/a_new_data_structure_for_cumulative_frequency_tables.pdf
optimization approach that transforms a complex problem into a sequence of simpler problems.
private static int lis(int[] arr) {
int max=1;
mem=new int[arr.length];
Arrays.fill(mem, 1);
for(int i=1;i<arr.length;i++){
for(int j=0;j<i;j++){
if(arr[j]<arr[i] && mem[i]<mem[j]+1){
mem[i]=mem[j]+1;
}
}
if(max<mem[i])max=mem[i];
}
return max;
}
Longest common subsequence : if X(i) = Y(j) D(i,j) =D( i-1,j-1 )+ 1 else : D(i,j) =Max(D( i-1,j ),D( i,j-1 )) Base cases: D( i,0 )=D( 0,j )=0
private static int lcs(String a, String b) {
mem = new int[a.length() + 1][b.length() + 1];
for (int i = 1; i <= a.length(); i++) {
for (int j = 1; j <= b.length(); j++) {
if (a.charAt(i - 1) == b.charAt(j-1)) {
mem[i][j] = mem[i - 1][j - 1] + 1;
} else {
mem[i][j] = Math.max(mem[i][j - 1], mem[i - 1][j]);
}
}
}
return mem[a.length()][b.length()];
}
Palindrome Min Insertions: minimum number of characters that need to be inserted to make it a palindrome
gap increasing D(i,j)=1+min( D(i+1,j),D(i,j-1) ) if str[i]!=str[j] D(i,j)=D(i+1,j-1) if str[i]==str[j]
private static int minInsertPalindrome(String string) {
for(int gap=1;gap<string.length();gap++){
for(int i=0,j=gap;j<string.length();i++,j++){
a[i][j] = (string.charAt(i) == string.charAt(j)) ? a[i + 1][j - 1]: Math.min(a[i][j - 1], a[i + 1][j]) + 1;
}
}
return a[0][string.length()-1];
}
Time complexity: O(N^2) Auxiliary Space: O(N^2)
Longest Subsequence Without Repetition :
static int[] mem = new int[256];
private static int longestSub(String a) {
Arrays.fill(mem, -1);
int pIndex;
int current = 1;
int max=1;
mem[a.charAt(0)] = 0;
for (int i = 1; i < a.length(); i++) {
pIndex=mem[a.charAt(i)];
//character not visited previously or it is not a part of Non repeating sequence
if(pIndex==-1 || i-current>pIndex){
current++;
}else{
//update max value if previous current value is greater than max till then
if(current>max){
max=current;
}
current=i-pIndex;
}
mem[a.charAt(i)]=i;
}
if(current>max){
max=current;
}
return max;
}
time complexity: O(mn) space complexity: O(mn)
MiniPonit Problem : http://www.topcoder.com/tc?module=ProblemDetail&rd=4710&pm=1996
Tree Dp : Problem: given a tree, color nodes black as many as possible without coloring two adjacent nodes Subproblems: First, we arbitrarily decide the root node π π΅π£: the optimal solution for a subtree having π£ as the root, where we color π£ black ππ£: the optimal solution for a subtree having π£ as the root, where we donβt color π£ The answer is max π΅π,ππ
Base case : Leaf
Subset DP : Prob: given a weighted graph with π nodes, find the shortest path that visits every node exactly once (Traveling Salesman Problem)
Brute force : O(n!) DP : O(pow(n,2)*pow(2,n)) D(g,v)=min(D(g-{v},u)+cost(u,v))
Most straightforward: http://www.spoj.com/problems/COINS/
static HashMap<Integer, Long> hm;
public static long coinsT(int i) {
hm = new HashMap<Integer, Long>();
if (i < 12) {
return i;
}
if (hm.containsKey(i)) {
return hm.get(i);
}
long temp = coinsT(i / 2) + coinsT(i / 3) + coinsT(i / 4);
hm.put(i, temp);
return temp;
}
More straightforward:
http://www.spoj.com/problems/ACODE/ RECOMMENDED
http://www.spoj.com/problems/MIXTURES/ RECOMMENDED
http://www.spoj.com/problems/MBALL
http://www.spoj.com/problems/PARTY
http://www.spoj.com/problems/KNAPSACK/
http://www.spoj.com/problems/MKBUDGET
http://www.spoj.com/problems/PIGBANK
http://www.spoj.com/problems/MMAXPER
http://www.spoj.com/problems/SCUBADIV/
http://www.spoj.com/problems/MINVEST
http://www.spoj.com/problems/BYTESM2/
http://www.spoj.com/problems/ROCK/
http://www.spoj.com/problems/NY10E/
http://www.spoj.com/problems/BABTWR/ http://www.spoj.com/problems/SQRBR/ http://www.spoj.com/problems/TWENDS/ http://www.spoj.com/problems/M3TILE/ http://www.spoj.com/problems/LISA/ http://www.spoj.com/problems/TRT/ NEW
Graph DP
http://www.spoj.com/problems/EDIST/
http://www.spoj.com/problems/CSTREET/
http://www.spoj.com/problems/CHICAGO/
http://www.spoj.com/problems/ACPC10D/
http://www.spoj.com/problems/DSUBSEQ/
http://www.spoj.com/problems/TAP2013J NEW
Mediumish: http://www.spoj.com/problems/JOCHEF/ http://www.spoj.com/problems/ACMAKER/ http://www.spoj.com/problems/MCOINS/ http://www.spoj.com/problems/CHOCOLA/ http://www.spoj.com/problems/MPILOT http://www.spoj.com/problems/MENU/ http://www.spoj.com/problems/CRSCNTRY http://www.spoj.com/problems/MBLAST/ http://www.spoj.com/problems/ANARC07G/ http://www.spoj.com/problems/IKEYB/ http://www.spoj.com/problems/PONY2/ NEW (do ACODE first) http://www.spoj.com/problems/PONY9/ NEW
Hard: http://www.spoj.com/problems/NGON http://www.spoj.com/problems/MYSTIC/ http://www.spoj.com/problems/MSTRING http://www.spoj.com/problems/CHOCDIST http://www.spoj.com/problems/GOSTONES NEW
http://www.spoj.com/problems/PT07Y
http://www.spoj.com/problems/TUTBFS http://www.spoj.com/problems/PT07Y http://www.spoj.com/problems/UCV2013H http://www.spoj.com/problems/LABYR1 http://www.spoj.com/problems/SHOP http://www.spoj.com/problems/BYTESE1 http://www.spoj.com/problems/BITMAP http://www.spoj.com/problems/PT07Z
basic:
http://www.spoj.com/problems/FCTRL/ http://www.spoj.com/problems/BSEARCH1/ http://www.spoj.com/problems/HANGOVER/ http://www.spoj.com/problems/PALIN/ spoj.com/problems/TEST spoj.com/problems/ADDREV spoj.com/problems/PRIME1
http://www.spoj.com/problems/ANARC09C/
for disjoint sets http://goo.gl/e9h857 http://goo.gl/orqp9H
finding median in unsorted array :
http://discuss.codechef.com/questions/1489/find-median-in-an-unsorted-array-without-sorting-it