题目要求分别以dfs和bfs遍历图,并且要满足字典序最小。
题目难度不大,但是要满足字典序最小,貌似用链式前向星写不了。改成vector用sort就可以过了。
AC代码:
/*
* @Author: hesorchen
* @Date: 2020-07-03 17:05:01
* @LastEditTime: 2020-09-02 21:40:38
* @Description: https://hesorchen.github.io/
*/
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <bitset>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI acos(-1)
#define PB push_back
#define ll long long
#define INF 0x3f3f3f3f
#define mod 1000000007
#define pll pair<ll, ll>
#define lowbit(abcd) (abcd & (-abcd))
#define max(a, b) ((a > b) ? (a) : (b))
#define min(a, b) ((a < b) ? (a) : (b))
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
#define FRE \
{ \
freopen("in.txt", "r", stdin); \
freopen("out.txt", "w", stdout); \
}
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
//head==============================================================================
long long ct = 1, ansdfsct, ansbfsct;
vector<long long> vec[100010];
long long visdfs[100010];
long long ansdfs[100010];
long long visbfs[100010];
long long ansbfs[100010];
void dfs(long long now)
{
long long sum = vec[now].size();
for (int i = 0; i < sum; i++)
{
long long v = vec[now][i];
if (!visdfs[v])
{
visdfs[v] = 1;
ansdfs[ansdfsct++] = v;
dfs(v);
}
}
}
queue<long long> q;
void bfs(long long s)
{
q.push(s);
while (q.size())
{
long long now = q.front();
q.pop();
long long sum = vec[now].size();
for (int i = 0; i < sum; i++)
{
long long v = vec[now][i];
if (!visbfs[v])
{
visbfs[v] = 1;
ansbfs[ansbfsct++] = v;
q.push(v);
}
}
}
}
int main()
{
long long n, m;
visdfs[1] = visbfs[1] = 1;
scanf("%lld %lld", &n, &m);
for (int i = 1; i <= m; i++)
{
long long u, v;
scanf("%lld %lld", &u, &v);
vec[u].push_back(v);
}
for (int i = 1; i <= n; i++)
sort(vec[i].begin(), vec[i].end());
dfs(1);
printf("1 ");
for (int i = 0; i < ansdfsct; i++)
printf("%lld ", ansdfs[i]);
printf(" \n");
bfs(1);
printf("1 ");
for (int i = 0; i < ansbfsct; i++)
printf("%lld ", ansbfs[i]);
return 0;
}
/*
*/