1 / 9
Feb 2020

I am confused for which input the output is coming wrong because it is not accepted on spoj as wrong answer is being shown.
My code is shown below–

#include<bits/stdc++.h>
using namespace std;
class Graph
{
int v;
list *adj;
public:
Graph(int v);
void addEdge(int v,int w);
void DFS(int s);
};
Graph::Graph(int v)
{
this->v=v;
adj=new list[v];
}
void Graph:: addEdge(int v,int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
void Graph:: DFS(int s)
{
int fvar=s;
int flag=1;
vector visited(v,false);
stack stk;
vectorparent(v,-1);
stk.push(s);
while(!stk.empty() && flag!=0){
s=stk.top();
stk.pop();
if(!visited[s]){
visited[s]=true;
}
list:: iterator it;
for(it=adj[s].begin();it!=adj[s].end();it++){

        if(!visited[*it]){
            parent[*it]=s;
            stk.push(*it);
        }
    if(visited[*it] && parent[s]!=*it){
        flag=0;
        break;
    }
    }
}
vector<bool>:: iterator it1;
for(it1=visited.begin();it1!=visited.end();it1++){
    if(visited[*it1]==false){
        flag=0;
        break;
    }
}
if(flag==0)
    cout<<"NO"<<endl;
else
    cout<<"YES"<<endl;

}
int main()
{
int i,m,x,y,v;
cin>>v>>m;
Graph g(v);
for(i=1;i<=m;i++){
cin>>x>>y;
g.addEdge(x-1,y-1);
}

g.DFS(x-1);
return 0;

}

Plz help. I have made my program by considering the vertices starting from zero thats why i have used x-1 and y-1 in addEdge function. Hope you understand.

  • created

    Feb '20
  • last reply

    Feb '20
  • 8

    replies

  • 1.1k

    views

  • 2

    users

  • 2

    links

You didn’t tell us what problem this is for. Even better, add a link to it.

Some of your code didn’t make it into the post correctly, so it won’t compile as it is. Please edit your post and indent the code by four spaces. Or paste it into IDEONE and share a link.

sorry for the inconvenience caused.

So according to you “NO” should be the answer to this question?
BTW is this a valid input because you have initially took 7 nodes but not considered 7th node anywhere.
If i am wrong what changes should i make in my program?

The problem simply says you’re given a graph. It does not say you’re given a connected graph.

You need to expand the logic to detect any graph that is not a tree.

thx a lot.
Now i added that logic of connected or disconnected graph.
It is accepted now.

Suggested Topics

Topic Category Replies Views Activity
Off-topic 1 79 Apr 9

Want to read more? Browse other topics in Off-topic or view latest topics.