evandrix's blog

By evandrix, 11 years ago, In English

Real algorithms using STL

Depth-first search (DFS)

/** Is it a tree?
Sample input:
    3 2
    1 2
    2 3
*/
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

#define MAX 100000
#define all(v) (v).begin(),(v).end()
typedef vector<int> vi;
typedef vector<vi> vvi;

vvi W; //W stores the graph(Adjacency List)
vi V;  //Array for storing whether a node is visited or not
// A set to store all the vertices.It is used to check if all
// vertices are visited or not
set<int> s;
int v,e,v1,v2,temp;

void dfs(int i) {
    if(!V[i]) {
        V[i] = true;
        for_each(all(W[i]), dfs);
    }
}

bool check_graph_connected_dfs(int start_vertex) {
    V = vi(v+1, false);
    dfs(start_vertex);
    return find(V.begin()+1, V.end(), 0) == V.end();
}

void mprintf(int i)
{
    printf("%d ", i);
}

int main()
{
    scanf("%d%d", &v,&e);

    vi::iterator it[MAX];
    if(e!=v-1)
    {
        printf("NO\n");
        return 0;
    }

    W.resize(MAX);
    for(int i=0; i<MAX; i++)
    {
        it[i]=W[i].begin();
    }

    for(int i=0; i<e; i++)
    {
        scanf("%d%d", &v1, &v2);
        s.insert(v1);
        s.insert(v2);
        temp = v1;
        it[v1] = W[v1].insert(it[v1], v2);
        it[v2] = W[v2].insert(it[v2], v1);
    }

    if(check_graph_connected_dfs(temp))
        printf("YES\n");
    else
        printf("NO\n");

//    for_each(V.begin()+1, V.end(), mprintf);
    return 0;
}
  • Vote: I like it
  • -5
  • Vote: I do not like it

| Write comment?