输入输出样例
输入 #1
8 9 1 2 1 3 1 4 2 5 2 6 3 7 4 7 4 8 7 8
输出 #1
1 2 5 6 3 7 8 4 1 2 3 4 5 6 7 8
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
struct Edge {
int u, v;//表示u指向v的关系;
};
vector<int>g[N];
vector<Edge>e;
bool vis[N];
int n, m;
bool cmp(Edge x,Edge y) {//
if (x.v == y.v)
return x.u < y.u;//v相同按u排序
else return x.v < y.v;//否则按v从小到大排序
}
void dfs(int x) {
vis[x] = true;
cout << x << ' ';
for (int i = 0;i < g[x].size();i++) {//每一条边,向下扩展
int j = e[g[x][i]].v;//找这条边对应的结点;即x号点的第i条边对应的结点是;
if (!vis[j]) {
dfs(j);
}
}
}
void bfs() {
memset(vis, 0, sizeof vis);
queue<int>q;
q.push(1);
vis[1] = true;
while (q.size()) {
int now = q.front();
cout << now << ' ';
q.pop();
for (int i = 0;i < g[now].size();i++) {
int j = e[g[now][i]].v;//这条边对应的结点;
if (!vis[j]) {
vis[j] = true;
q.push(j);
}
}
}
}
int main()
{
cin >> n >> m;
Edge edge;
//边的建立
for (int i = 0;i < m;i++) {
int a, b;
cin >> a >> b;
edge.u = a, edge.v = b;
e.push_back(edge);//初始化存边的e数组
}
sort(e.begin(), e.end(), cmp);
//
for (int i = 0;i < m;i++) {
g[e[i].u].push_back(i); //初始化g数组,在g[e[i].u](也就是i号边的起点g[i].u连接的边的数组)中存入i号边
}
dfs(1);
cout << endl;
bfs();
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10;
typedef pair<int, int> PII;
int n, m;
int h[N], e[M], ne[M], idx;
bool st[N];
PII edge[M];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u)
{
cout << u << ' ';
st[u] = true;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j])
dfs(j);
}
}
void bfs(int start)
{
st[start] = true;
queue<int> q;
q.push(start);
while (q.size())
{
int t = q.front();
q.pop();
cout << t << ' ';
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j])
q.push(j), st[j] = true;
}
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
edge[i] = {a, b};
}
sort(edge, edge + m);
reverse(edge, edge + m);
// for(int i=0;i<m;i++)
// cout<<edge[i].x<<' '<<edge[i].y<<endl;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++)
add(edge[i].x, edge[i].y);
dfs(1);
cout << endl;
memset(st, false, sizeof st);
bfs(1);
cout << endl;
return 0;
}