Showing posts with label Algorithms. Show all posts
Showing posts with label Algorithms. Show all posts

Saturday, 23 June 2018

Depth First Search DFS (code (C++)

This algorithm can transverse a graph and find all the reachable points


 1  #include<bits/stdc++.h>
 2  using namespace std;
 3  int n,e;
 4  vector<int>g[128];
 5  bool seen[128];
 6 
 7  void dfs(int u){
 8  seen[u] = true;
 9  cout<<u<<" ";
10  for(int i=0;i<g[u].size();i++){
11      int v = g[u][i];
12      if(!seen[v])dfs(v);
13  printf("\n");
14  }
15 
16  }
17  int main(){
18  cin>>n>>e;
19  for(int i=0;i<n;i++){
20      int u,v;
21      cin>>u>>v;
22      g[u].push_back(v);
23  }
24  for(int i = 1;i<=n;i++ ){
25      if(!seen[i]){
26          dfs(i);
27      }
28  }
29 
30  return 0;}

Sunday, 24 September 2017

Finding Array of Prime and Factors using Sieve of Eratosthenes Algorithm in C++

Theory: Using the sieve of Eratosthenes find an array of prime numbers.

Explanation:

1.Declare an int array sieve[]
2.Using the Sieve of Eratosthenes algorithm an array of prime can be obtained.Again factors of non prime can also be obtained;
3.sieve[i] == 0 : i is a prime number.
4. When not equal to zero the factor is displaced within the array element.

Code
#include <bits/stdc++.h>
using namespace std;
int sieve[100];
int main(){
int n;

cin>>n;
for(int x=2; x<=n; x++){
if(sieve[x]){
continue;
}
for(int i=2*x;i<=n;i+=x){
sieve[i]=x;
}
}

cout<<"Prime factors is those elements with 0 and other elements are factors";
for(int i=2;i<=n;i++){

    cout<<i<<" "<<sieve[i]<<endl;
}
return 0;}


Spoj Problem ACMCEG2C - Pick the candies (C++)

  The problem link may be found here.       Explanation: Use Deque to keep track of elements of the variety of candies. If i is gre...