#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;
}
图的bfs,dps,拓扑排序
最新推荐文章于 2022-05-25 17:01:06 发布