图的广度优先搜索和深度优先搜索
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 5001
using namespace std;
typedef long long lld;
struct Node
{
vector<int> adj;
};
Node graf[MAX_N];
bool mark[MAX_N];
inline void BFS(int start)
{
queue<int> bfs_queue;
bfs_queue.push(start);
while( !bfs_queue.empty())
{
int xt = bfs_queue.front();
bfs_queue.pop();
mark[xt] = true;
cout<< "Traversing Node ID " << xt <<endl;
for(int i=0; i<graf[xt].adj.size(); i++)
{
if( !mark[graf[xt].adj[i]])
{
bfs_queue.push(graf[xt].adj[i]);
mark[graf[xt].adj[i]] = true;
}
}
}
}
inline void DFS(int start)
{
stack<int> dfs_stek;
dfs_stek.push(start);
while(!dfs_stek.empty())
{
int xt = dfs_stek.top();
dfs_stek.pop();
mark[xt] = true;
cout << "Traversing Node ID " << xt << endl;
for(int i=0; i<graf[xt].adj.size(); i++)
{
if(!mark[graf[xt].adj[i]])
{
dfs_stek.push(graf[xt].adj[i]);
mark[graf[xt].adj[i]] = true;
}
}
}
}
int main()
{
graf[0].adj.push_back(1);
graf[0].adj.push_back(2);
graf[2].adj.push_back(3);
graf[3].adj.push_back(4);
cout<< "DFS" <<endl;
cout<< "BFS" <<endl;
BFS(0);
return 0;
}
Dijkstra算法
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 100001
#define INF 987654321
using namespace std;
typedef long long lld;
int n;
struct Node
{
int dist;
vector<int> adj;
vector<int> weight;
};
Node graf[MAX_N];
bool mark[MAX_N];
struct pq_entry
{
int node, dist;
bool operator<(const pq_entry &a) const
{
if(dist != a.dist)
return (dist > a.dist);
return (node > a.node);
}
};
inline void dijkstra(int source)
{
priority_queue<pq_entry> pq;
pq_entry P;
for(int i=0; i<n; i++)
{
if(i == source)
{
graf[i].dist = 0;
P.node = i;
P.dist = 0;
pq.push(P);
}
else
{
graf[i].dist = INF;
}
}
while(!pq.empty())
{
pq_entry curr = pq.top();
pq.pop();
int nod = curr.node;
int dis = curr.dist;
for(int i=0; i<graf[nod].adj.size(); i++)
{
if(!mark[graf[nod].adj[i]])
{
int nextNode = graf[nod].adj[i];
if(dis + graf[nod].weight[i] < graf[nextNode].dist)
{
graf[nextNode].dist = dis + graf[nod].weight[i];
P.node = nextNode;
P.dist = graf[nextNode].dist;
pq.push(P);
}
}
}
mark[nod] = true;
}
}
int main(int argc, char const *argv[])
{
n = 4;
graf[0].adj.push_back(1);
graf[0].weight.push_back(5);
graf[1].adj.push_back(0);
graf[1].weight.push_back(5);
graf[1].adj.push_back(2);
graf[1].weight.push_back(5);
graf[2].adj.push_back(1);
graf[2].weight.push_back(5);
graf[2].adj.push_back(3);
graf[2].weight.push_back(5);
graf[3].adj.push_back(2);
graf[3].weight.push_back(5);
graf[3].adj.push_back(1);
graf[3].weight.push_back(6);
graf[1].adj.push_back(3);
graf[1].weight.push_back(6);
dijkstra(0);
printf("%d\n",graf[3].dist);
return 0;
}