用vector存图并执行相关操作
#include <vector>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <iterator>
#include <iostream>
#include <queue>
#define print(a) cout << #a << " : " << a << endl
using namespace std;
struct node
{
int v;
int w;
node(){}
node(int v, int w):v(v), w(w){}
};
vector<node> vc[1000];
bool vis[100];
void dfs(int cur) //深度遍历
{
cout << cur << " "; //访问cur节点
for(int i = 0; i < vc[cur].size(); i++)
{
int v = vc[cur][i].v;
if(vis[v] == false)
{
vis[v] = true;
dfs(v);
}
}
}
void out_deg(int vexNum) //求每一个点的出度
{
for(int i = 1; i <= vexNum; i++)
{
cout << i << " ' out_deg is : " << vc[i].size() << endl;
}
}
void bfs() //广度优先遍历
{
queue<node> q;
q.push(node(1, 0));
while(!q.empty())
{
node top = q.front(); q.pop();
cout << top.v << " "; //访问top节点
for(int i = 0; i < vc[top.v].size(); i++)
{
int v = vc[top.v][i].v;
int w = vc[top.v][i].w;
if(vis[v] == false)
{
vis[v] = true;
q.push(node(v, w));
}
}
}
}
void test(int vexNum)
{
out_deg(vexNum);cout << endl;
vector<node>::iterator it;
for(it = vc[3].begin(); it != vc[3].end(); NULL) //删除点3 后面接的点5这条边
{
if(5 == (*it).v)
it = vc[3].erase(it); //注意删除后it指向下一个点, 所以必须这样
else
it++;
}
for(int i = 1; i <= vexNum; i++) //输出没个点所能到达的边
{
cout << i << "--->: ";
for(int j =0; j < vc[i].size(); j++)
cout << vc[i][j].v << " ";
cout << endl;
}
memset(vis, false, sizeof(vis));
dfs(1);cout << endl;
memset(vis, false, sizeof(vis));
bfs();cout << endl;
}
int main()
{
int vexNum, edgeNum;
cin >> vexNum >> edgeNum;
for(int i = 0; i < edgeNum; i++)
{
int u, v, w;
cin >> u >> v >> w;
vc[u].push_back(node(v, w));
}
test(vexNum);
return 0;
}