P5318 【深基18.例3】查找文献
在排序时一定要看好数组的个数到底是m还是n,尽量在命名变量的时候不要选择太相似的,如aa和a,bb和b,就因为这小小的两点卡了我一下午。


题目:

代码1:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
const int N = 1000010;
long long h[N],e[N*2],ne[N*2],idx;
long long n,m;
long long path[N];
long long q[N];
bool st[N];
long long t;
struct node{
long long a,b;
};
node arr[N];
//先对输入数据排序再建边
bool cmp(node aa,node bb){
if(aa.a == bb.a) return aa.b > bb.b;
return aa.a < bb.a;
}
void add(int a,int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
return;
}
void dfs(int u){
st[u] = true;
for(int i=h[u];i!=-1;i=ne[i]){
int j = e[i];
if(!st[j]){
path[t++] = j;
dfs(j);
}
}
return;
}
void bfs(int u){
int hh = 0,tt = -1;
q[++tt] = u;
st[u] = true;
while(hh <= tt){
int x = q[hh++];
for(int i = h[x];i != -1;i = ne[i]){
int j = e[i];
if(!st[j]){
st[j] = true;
q[++tt] = j;
}
}
}
return;
}
int main()
{
scanf("%lld%lld",&n,&m);
memset(h,-1,sizeof(h));
for(int i=0;i<m;i++)
{
int a,b;
scanf("%lld%lld",&arr[i].a,&arr[i].b);
}
sort(arr,arr+m,cmp);
for(int i=0;i<m;i++)
{
add(arr[i].a,arr[i].b);
}
//已知从编号1开始
path[t++] = 1;
dfs(1);
for(int i=0;i<n;i++){
printf("%lld ",path[i]);
}
cout<<endl;
memset(st,false,sizeof(st));
bfs(1);
for(int i=0;i<n;i++){
printf("%lld ",q[i]);
}
return 0;
}
结果:
