图的bfs,dps,拓扑排序

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define ll long long
#define inf 0x3f3f3f3f
#define sd(a) scanf("%d",&a)
#define mem(a) memset(a,0,sizeof(a))
const int maxn = 1e5+10;
const int mod = 1e9+7;

using namespace std;

struct edge;
struct Node;
struct Graph;

struct Graph
{
    map<int,Node>nodes;//点集(编号与对应点)
    set<edge>edges;//边集
};

struct Node//点
{
    int value;
    int in;//入度(被指向)
    int out;//出度(指向)
    int par;
    set<edge>edges;//边集
    set<Node>next;//由该点指向其他点的集合
    friend bool operator < (const Node& n1, const Node& n2)
    {
        return n1. value < n2. value;
    }
};

struct edge//边
{
    int weight;//权值
    Node from;//常用于有向图
    Node to;//若在无向图,a-b=a->b+b->a
};


void bfs(Node node)//广搜
{
    //if(node == NULL)
        //return;
    queue<Node>q;
    set<Node>s;
    while(!q.empty())q.pop();
    while(!s.empty())s.clear();
    q.push(node);
    s.insert(node);
    while(!q.empty())
    {
        Node cur = q.front();
        q.pop();
        cout<<cur.value<<endl;
        for(Node next:cur.next)//
            if(!s.count(next))
            {
                s.insert(next);
                q.push(next);
            }
    }
}

void dps(Node node)//深度优先遍历
{
    stack<Node>St;
    set<Node>s;
    St.push(node);
    s.insert(node);
    cout<<node.value<<endl;
    while(!St.empty())
    {
        Node cur = St.top();
        St.pop();
        for(Node next:cur.next)
        {
            if(!s.count(next))
            {
                St.push(cur);
                St.push(next);
                s.insert(next);
                cout<<next.value<<endl;
                break;
            }
        }
    }
}

void Topology(Graph graph)//拓扑排序:仅能用于无环图
{
    map<Node,int>InMap;//点集:点以及他的入度
    queue<Node>ZeroInQ;//入度为0的点才可进
    vector<Node>result;
    for(int i = 0;i < (int)graph.nodes.size();i++)
    {
        Node cur = graph.nodes[i];
        if(cur.in == 0)
            ZeroInQ.push(cur);
    }
    while(!ZeroInQ.empty())
    {
        Node cur = ZeroInQ.front();
        cout<<cur.value<<endl;
        ZeroInQ.pop();
        result.push_back(cur);
        for(Node next:cur.next)
        {
            InMap.insert(map<Node,int>::value_type(next,next.in - 1));
            if(InMap[next] == 0)
            {
                ZeroInQ.push(next);
                cout<<next.value<<endl;
            }

        }
    }
}


int main()
{
    Node a;
    a.value = 1;
    Node b;
    b.value = 2;
    a.next.insert(b);
    dps(a);
    //cout << (int)(1&3) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值