P5318 【深基18.例3】查找文献(图的遍历)还没写完,留着再看吧

本文介绍了一个C++程序,通过先对输入数据中的节点按特定条件排序,然后构建边并实现深度优先搜索和广度优先搜索,解决查找路径的问题。重点在于代码实现和数据处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值