kosaraju algorithm:
Problem statement: Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, Find the number of strongly connected components in the graph.
while implementing this code I am getting a segmentation fault. Where is the error in this code?
void dfs(int node,vector<int>adj[],stack<int>&st,vector<int>&vis){
vis[node]=1;
for(auto it: adj[node]){
if(!vis[it]){
dfs(it,adj,st,vis);
}
}
st.push(node);
}
void revdfs(int node,vector<int>trs[],vector<int>&vis){
vis[node]=1;
for(auto it: trs[node]){
if(!vis[it]){
revdfs(it,trs,vis);
}
}
}
int kosaraju(int V, vector<int> adj[])
{
stack<int>st;
vector<int>vis(V+1,0);
for(int i=0; i<V;i++){
if(!vis[i])
dfs(i,adj,st,vis);
}
int cnt=0;
vector<int> transpose[V+1];
for(int i = 1;i<=V;i++) {
vis[i] = 0;
for(auto it: adj[i]) {
transpose[it].push_back(i);
}
}
while(!st.empty()){
int node=st.top();
st.pop();
if(!vis[node]){
cnt++;
revdfs(node,transpose,vis);
}
}
return cnt;
Related
The below code in c++ is to find the distance between any two nodes in a graph but there is some logical error where I tried to find but can't. Everything seems to be perfect but I can say that there is something wrong with a break inside if condition inside for loop which is inside while(s.!empty()).
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int find_distance(int link[100][100],int start,int dest,int n,int e)
{
start=start-1;
dest=dest-1;
if(start==dest)return 0;
int visited[100];
int distance;
for(int i=0;i<n;i++)
{
visited[i]=0;
}
stack<int>s;
int k;s.push(start);
visited[start]=1;
bool found=false;
int count =0;
while(!s.empty())
{
k=s.top();
int i;
int check_point=1;
for(i=0;i<n;i++)
{
if(link[k][i]==1 && visited[i]!=1)
{
s.push(i);
count ++;
check_point=0;
if(i==dest)
{
cout<<"found";
found=true;
}
break;
}
}
if(check_point==1)
{
s.pop();
count--;
}
if(found)break;
}
return count;
}
int main()
{
int n,e,a,b;
int link[100][100];
cout<<"enter the number of vertices and edges";
// cin>>n>>e;
n=5;e=4;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
link[i][j]=0;
else
link[i][j]=INT_MAX;
cout<<link[i][j]<<" ";
}
cout<<endl;
}
int input[4][2]={{1,2},{1,3},{2,4},{2,5}};
for(int i=0;i<e;i++)
{
a=input[i][0];
b=input[i][1];
link[a-1][b-1]=1;
link[b-1][a-1]=1;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<link[i][j]<<" ";
}
cout<<endl;
}
while(true) {
cout<<endl<<"enter the starting point .. ";
int start;
cin>>start;
int dest;
cout<<endl<<"enter the destination point .. ";
cin>>dest;
int distance = find_distance(link,start,dest,n,e);
cout<<endl<<"distance is "<<distance;
}
return 0;
}
Find all reachable nodes from every node present in a given set
Given an undirected graph and a set of vertices, find all reachable nodes from every vertex present in the given set.
#include <bits/stdc++.h>
using namespace std;
class Graph
{
public:
int V;
list<int> *adj;
Graph(int );
void addEdge(int, int);
vector<int> BFS(int, int, int []);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V+1];
}
void Graph::addEdge(int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int> Graph::BFS(int componentNum, int src,int visited[])
{
queue<int> queue;
queue.push(src);
visited[src] = componentNum;
vector<int> reachableNodes;
while(!queue.empty())
{
int u = queue.front();
queue.pop();
reachableNodes.push_back(u);
for (auto itr = adj[u].begin();itr != adj[u].end(); itr++)
{
if (!visited[*itr])
{
visited[*itr] = componentNum;
queue.push(*itr);
}
}
}
return reachableNodes;
}
void displayReachableNodes(int n,unordered_map <int, vector<int>> m)
{
vector<int> temp = m[n];
for (int i=0; i<temp.size(); i++)
cout << temp[i] << " ";
cout << endl;
}
void findReachableNodes(Graph g, int arr[], int n)
{
int V = g.V;
int visited[V+1];
memset(visited, 0, sizeof(visited));
unordered_map <int, vector<int> > m;
int componentNum = 0;
for (int i = 0 ; i < n ; i++)
{
int u = arr[i];
if (!visited[u])
{
componentNum++;
m[visited[u]] = g.BFS(componentNum, u, visited);
}
//cout << "Reachable Nodes from " << u <<" are\n";
displayReachableNodes(visited[u], m);
}
}
int main()
{
int V = 7;
Graph g(V);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(3, 1);
g.addEdge(5, 6);
g.addEdge(5, 7);
int arr[] = {2, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
findReachableNodes(g, arr, n);
return 0;
}
Same code in ideone the output is coming and visible but in code blocks its not visible or coming. Why is this happening?
I am solving a problem on my college judge where i have to all lis sequences. The n is very small so, i am generating all subsets and if they are increasing and of longest length, i am printing it. What's wrong in my code? Or may be any problem with order?
#include<iostream>
#include<cmath>
#include<algorithm>
#include<sstream>
#include<vector>
#include<map>
using namespace std;
int a[100005];
int l[100005];
vector< vector<int> > V;
int main()
{
int n,r,c;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
l[i]=1;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
if(a[i]>a[j]&&l[i]<l[j]+1)
{
l[i]=l[j]+1;
}
}
}
vector<int> v;
r=0;
int cnt=0;
for(int i=0;i<pow(2,n);i++)
{
for(int j=0;j<n;j++)
{
if(i & (1<<j))
{
v.push_back(a[j]);
}
}
int f=0;
if(v.size()==*max_element(l,l+n))
{
int ss=v.size();
for(int x=0;x<ss-1;x++)
{
if(v[x]>=v[x+1])
{
f=-1;
break;
}
}
if(f==0)
{
V.push_back(v);
}
}
v.clear();
}
for(int i=0;i<V.size();i++)
{
for(int j=0;j<V[i].size();j++)
{
cout<<V[i][j];
if(j!=V[i].size()-1)
cout<<" ";
}
cout<<endl;
}
return 0;
}
There are 10 balloons and each balloon has some point written onto it. If a customer shoots a balloon, he will get points equal to points on left balloon multiplied by points on the right balloon. A Customer has to collect maximum points in order to win this game. What will be maximum points and in which order should he shoot balloons to get maximum points ?
Please note that if there is only one balloon then you return the points on that balloon.
I am trying to check all 10! permutations in order to find out maximum points. Is there any other way to solve this in efficient way ?
As i said in the comments a Dynamic programming solution with bitmasking is possible, what we can do is keep a bitmask where a 1 at a bit indexed at i means that the ith baloon has been shot, and a 0 tells that it has not been shot.
So a Dynamic Programming state of only mask is required, where at each state we can transition to the next state by iterating over all the ballons that have not been shot and try to shoot them to find the maximum.
The time complexity of such a solution would be : O((2^n) * n * n) and the space complexity would be O(2^n).
Code in c++, it is not debugged you may need to debug it :
int n = 10, val[10], dp[1024]; //set all the values of dp table to -1 initially
int solve(int mask){
if(__builtin_popcount(mask) == n){
return 0;
}
if(dp[mask] != -1) return dp[mask];
int prev = 1, ans = 0;
for(int i = 0;i < n;i++){
if(((mask >> i) & 1) == 0){ //bit is not set
//try to shoot current baloon
int newMask = mask | (1 << i);
int fwd = 1;
for(int j = i+1;j < n;j++){
if(((mask >> j) & 1) == 0){
fwd = val[j];
break;
}
}
ans = max(ans, solve(newMask) + (prev * fwd));
prev = val[i];
}
}
return dp[mask] = ans;
}
#include<iostream>
using namespace std;
int findleft(int arr[],int n,int j ,bool isBurst[],bool &found)
{
if(j<=0)
{
found=false;
return 1;
}
for(int i=j-1;i>=0;i--)
{
if(!isBurst[i])
{
return arr[i];
}
}
found = false;
return 1;
}
int findright(int arr[],int n,int j,bool isBurst[],bool &found)
{
if(j>=n)
{
found = false;
return 1;
}
for(int i= j+1;i<=n;i++)
{
if(!isBurst[i])
{
return arr[i];
}
}
found=false;
return 1;
}
int calc(int arr[],int n,int j,bool isBurst[])
{
int points =0;
bool leftfound=true;
bool rightfound=true;
int left= findleft( arr, n-1, j,isBurst , leftfound);
int right = findright( arr,n-1, j,isBurst, rightfound);
if(!leftfound && !rightfound)
{
points+=arr[j];
}
else
{
points+=left*right*arr[j];
}
return points;
}
void maxpoints(int arr[],int n,int cp,int curr_ans,int &ans,int count,bool isBurst[])
{
if(count==n)
{
if(curr_ans>ans)
{
ans=curr_ans;
return;
}
}
for(int i=0;i<n;i++)
{
if(!isBurst[i])
{
isBurst[i]=true;
maxpoints(arr,n,i,curr_ans+calc(arr,n,i,isBurst),ans,count+1,isBurst);
isBurst[i]=false;
}
}
}
int main()
{
int n;
cin>>n;
int ans=0;
int arr[n];
bool isBurst[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
isBurst[i]=false;
}
maxpoints(arr,n,0,0,ans,0,isBurst);
cout<<ans;
return 0;
}
Given a horizontal section of wall , and N layers of paints applied from co-ordinates Xi to Yi , Output the distinct number of layers visible.
Here is the problem link http://www.spoj.com/problems/POSTERS/
Here is my solution http://ideone.com/gBJKnL
Approach :
I tried solving the problem by lazily updating child node values through a Segment Tree , the most recent value replaces the older one in their lazy updates. This way only the recent paint gets applied into the horizontal cross-section. although the code works fine on custom test cases , It takes a lot of memory and gets aborted by the Online Judge .
#include <iostream>
#include <set>
#include <vector>
#define MAX 10000000+100
typedef long long int ll;
using namespace std;
ll Tree[3*MAX],lazy[MAX*2];
void Update(ll s,ll start,ll end,ll left,ll right,ll value)
{
if(lazy[s]!=0)
{
Tree[s]=(lazy[s]*(end-start+1));
if(start!=end)lazy[2*s+1]=lazy[s],lazy[s*2+2]=lazy[s];
lazy[s]=0;
}
if(start>end||left>end||right<start)return;
if(start>=left&&end<=right)
{
Tree[s] = (value*(end-start+1));
if(start!=end)
{
lazy[2*s+1]=value;
lazy[2*s+2]=value;
}
return ;
}
ll mid=(start+end)/2;
Update(2*s+1,start,mid,left,right,value);
Update(2*s+2,mid+1,end,left,right,value);
Tree[s] = Tree[s*2+1]+Tree[2*s+2];
}
ll Read(ll s,ll start,ll end,ll left,ll right)
{
if(start>end||start>right||end<left)return 0;
if(lazy[s]!=0)
{
Tree[s]=(lazy[s]*(end-start+1));
if(start!=end)
{
lazy[2*s+1]=lazy[s];
lazy[2*s+2]=lazy[s];
}
lazy[s]=0;
}
if(start>=left&&end<=right)return Tree[s];
else return (Read(2*s+1,start,(start+end)/2,left,right)+Read(2*s+2,1+((start+end)/2),end,left,right));
}
int main() {
// your code goes here
ll t;
cin>>t;
while(t--)
{
ll n,z=1,li=-1;
cin>>n;
vector<pair<ll,ll> > b;
for(ll i=0;i<n;i++)
{
ll u,v;
li = max(li,v);
cin>>u>>v;
b.push_back(make_pair(u-1,v-1));
}
for(auto v: b)
Update(0,0,li+2,v.first,v.second,z++);
set<ll> a;
for(ll i=0;i<li+2;i++)cout<<Read(0,0,li+2,i,i)<<" ",a.insert(Read(0,0,li+2,i,i));
cout<<endl;
cout<<a.size()-1<<endl;
}
return 0;
}
Here is how you should be doing it:
#include <bits/stdc++.h>
#define mx 400005
using namespace std;
int tr[mx], lz[mx];
int t, n, l, r;
void update(int node, int s, int e, int l, int r, int val)
{
if(lz[node]!=0)
{
tr[node]=lz[node];
if(s!=e)
{
lz[node*2]=lz[node];
lz[node*2+1]=lz[node];
}
lz[node]=0;
}
if(s>e || r<s || l>e)
return;
if(s>=l && e<=r)
{
tr[node]=val;
if(s!=e)
{
lz[2*node]=val;
lz[2*node+1]=val;
}
return;
}
int m=s+(e-s)/2;
update(2*node,s,m,l,r,val);
update(2*node+1,m+1,e,l,r,val);
tr[node]=val;
//tr[node]=max(tr[2*node],tr[2*node+1]);
}
int query(int node, int s, int e, int l, int r)
{
if(r<s || e<l)
return 0;
if(lz[node]!=0)
{
tr[node]=lz[node];
if(s!=e)
{
lz[node*2]=lz[node];
lz[node*2+1]=lz[node];
}
lz[node]=0;
}
if(l<=s && r>=e)
return tr[node];
int m=s+(e-s)/2;
return query(2*node,s,m,l,r)+query(2*node+1,m+1,e,l,r);
}
int main()
{
//cout << "Hello world!" << endl;
cin>>t;
while(t--)
{
for(int i=0; i<mx; i++) tr[i]=0;
cin>>n;
int lr[n+1][2];
map<int,bool> mark;
vector<int> vec;
//int c=0;
for(int i=0; i<n; i++)
{
cin>>l>>r;
lr[i][0]=l;
lr[i][1]=r;
if(mark[l]==0)
{
vec.push_back(l);
mark[l]=1;
}
if(mark[r]==0)
{
vec.push_back(r);
mark[r]=1;
}
}
sort(vec.begin(), vec.end());
map<int,int> mp;
int c=1;
for(int i=0; i<vec.size(); i++)
mp[vec[i]]=c++;
for(int i=0; i<n; i++)
{
//cout<<mp[lr[i][0]]<<" "<<mp[lr[i][1]]<<"\n";
update(1,1,vec.size(),mp[lr[i][0]],mp[lr[i][1]],i+1);
}
set<int> ans;
for(int i=1; i<=vec.size(); i++)
{
//cout<<query(1,1,vec.size(),i,i)<<" ";
ans.insert(query(1,1,vec.size(),i,i));
}
int k = ans.size();
if(ans.find(0) != ans.end())
k--;
printf("%d\n",k);
}
return 0;
}