判断图有无环路

// A C++ Program to detect cycle in a graph
#include<iostream>
#include <list>
#include <limits.h>

using namespace std;

class Graph
{
    int V;    // No. of vertices
    list<int> *adj;    // Pointer to an array containing adjacency lists
    bool isCyclicUtil(int v, bool visited[], bool *rs);  // used by isCyclic()
public:
    Graph(int V);   // Constructor
    void addEdge(int v, int w);   // to add an edge to graph
    bool isCyclic();    // returns true if there is a cycle in this graph
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}

// This function is a variation of DFSUytil() in http://www.geeksforgeeks.org/archives/18212
bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack)
{
    if(visited[v] == false)
    {
        // Mark the current node as visited and part of recursion stack
        visited[v] = true;
        recStack[v] = true;

        // Recur for all the vertices adjacent to this vertex
        list<int>::iterator i;
        for(i = adj[v].begin(); i != adj[v].end(); ++i)
        {
            if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) )
                return true;
            else if (recStack[*i])
                return true;
        }

    }
    recStack[v] = false;  // remove the vertex from recursion stack
    return false;
}

// Returns true if the graph contains a cycle, else false.
// This function is a variation of DFS() in http://www.geeksforgeeks.org/archives/18212
bool Graph::isCyclic()
{
    // Mark all the vertices as not visited and not part of recursion
    // stack
    bool *visited = new bool[V];
    bool *recStack = new bool[V];
    for(int i = 0; i < V; i++)
    {
        visited[i] = false;
        recStack[i] = false;
    }

    // Call the recursive helper function to detect cycle in different
    // DFS trees
    for(int i = 0; i < V; i++)
        if (isCyclicUtil(i, visited, recStack))
            return true;

    return false;
}

int main()
{
    //freopen("test.txt", "r", stdin);

    int n, m;
    while (~scanf("%d%d", &n, &m)) {
        Graph g(n);

        int src, des;

        for (int i = 0; i < m; i++) {
            cin >> src >> des;
            //顶点编号为0~n-1, 输入的边为1~n,所以这里要-1
            g.addEdge(src - 1, des - 1);
        }

        if(g.isCyclic())
            cout << "yes\n";
        else
            cout << "no\n";
    }



    return 0;
}

DFS

    void Graph::DFSUtil(int v, bool visited[])
{
    // Mark the current node as visited and print it
    visited[v] = true;
    cout << v << " ";

    // Recur for all the vertices adjacent to this vertex
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFSUtil(*i, visited);
}

// DFS traversal of the vertices reachable from v. 
// It uses recursive DFSUtil()
void Graph::DFS(int v)
{
    // Mark all the vertices as not visited
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;

    // Call the recursive helper function to print DFS traversal
    DFSUtil(v, visited);
}

BFS

    void addEdge(vector<int> adj[], int u, int v)
    {
        adj[u].push_back(v);
    }

    // A utility function to do BFS of graph
    // from a given vertex u.
    void BFSUtil(int u, vector<int> adj[],
                vector<bool> &visited)
    {

        // Create a queue for BFS
        list<int> q;

        // Mark the current node as visited and enqueue it
        visited[u] = true;
        q.push_back(u);

        // 'i' will be used to get all adjacent vertices 4
        // of a vertex list<int>::iterator i;

        while(!q.empty())
        {
            // Dequeue a vertex from queue and print it
            u = q.front();
            cout << u << " ";
            q.pop_front();

            // Get all adjacent vertices of the dequeued
            // vertex s. If an adjacent has not been visited, 
            // then mark it visited and enqueue it
            for (int i = 0; i != adj[u].size(); ++i)
            {
                if (!visited[adj[u][i]])
                {
                    visited[adj[u][i]] = true;
                    q.push_back(adj[u][i]);
                }
            }
        }
    }

    // This function does BFSUtil() for all 
    // unvisited vertices.
    void BFS(vector<int> adj[], int V)
    {
        vector<bool> visited(V, false);
        for (int u=0; u<V; u++)
            if (visited[u] == false)
                BFSUtil(u, adj, visited);
    }

Kruskal

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int M=7e6+7;
    struct node
    {
        int a,b,val;
    } Q[M];
    int fa[M];
    int Rd()
    {
        int res=0;char c;
        while(c=getchar(),!isdigit(c));
        do
        {
            res=(res<<3)+(res<<1)+(c^48);
        }while(c=getchar(),isdigit(c));
        return res;
    }
    bool cmp(struct node a,struct node b){
        return a.val<b.val;
    }
    int getfa(int v){
        if(fa[v]!=v)fa[v]=getfa(fa[v]);
        return fa[v];
    }
    int main()
    {
    //    freopen("test.txt", "r", stdin);
        int i,j,n,m,x,y;
        while (~scanf("%d%d",&n,&m)) {

            for (i = 1; i <= m; i++) {
                Q[i].a = Rd();
                Q[i].b = Rd();
                Q[i].val = Rd();
            }
            sort(Q + 1, Q + m + 1, cmp);
            for (i = 1; i <= n; i++) {
                fa[i] = i;
            }
            int sum = 0, cut = 0;
            for (i = 1; i <= m; i++) {
                x = getfa(Q[i].a);
                y = getfa(Q[i].b);
                if (x == y)continue;
                sum += Q[i].val;
                if (++cut == n - 1)break;
                fa[x] = y;
            }
            printf("%d\n", sum);
        }
        return 0;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值