【数据结构1-4】图的基本应用

这篇博客主要探讨了图在计算机科学中的基本应用,包括查找文献、图的遍历、最大食物链计数、最长路径问题等。通过分析洛谷平台上的相关题目,如P5318、P3916、P1113等,阐述了拓扑排序、最远距离计算等算法,并提供了参考资源和解决方案。
摘要由CSDN通过智能技术生成

P5318 【深基18.例3】查找文献

题目链接:P5318 【深基18.例3】查找文献 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;

struct edge {
	int u, v;
};
vector<int>e[100010];
vector<edge>s;
bool vis[100010];

bool cmp(edge e1, edge e2) {
	if (e1.v == e2.v) {
		return e1.u < e2.u;
	} else {
		return e1.v < e2.v;
	}
}

void dfs(int x) {
	vis[x] = 1;
	cout << x << ' ';
	for (int i = 0; i < e[x].size(); i++) {
		int y = s[e[x][i]].v;
		if (!vis[y]) {
			dfs(y);
		}
	}
}

void bfs(int x) {
	queue<int>q;
	q.push(x);
	cout << x << ' ';
	vis[x] = 1;
	while (!q.empty()) {
		int y = q.front();
		q.pop();
		for (int i = 0; i < e[y].size(); i++) {
			int z = s[e[y][i]].v;
			if (!vis[z]) {
				q.push(z);
				cout << z << ' ';
				vis[z] = 1;
			}
		}
	}
}

int main() {
	int n, m;
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		edge e1;
		cin >> e1.u >> e1.v;
		s.push_back(e1);
	}
	sort(s.begin(), s.end(), cmp);
	for (int i = 0; i < m; i++) {
		//e[a][b]=c,来表示顶点a的第b条边是c号边
		e[s[i].u].push_back(i);
	}
	dfs(1);
	cout << endl;
	memset(vis, 0, sizeof(vis));
	bfs(1);
	return 0;
}

P3916 图的遍历

题目链接:P3916 图的遍历 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include <iostream>
#include <vector>
using namespace std;
vector<int>G[100010];

int a[100010];//第i点能到达的最大节点
void dfs(int x, int d) {
	if (a[x]) {
		return;
	}
	a[x] = d;
	for (int i = 0; i < G[x].size(); i++) {
		dfs(G[x][i], d);
	}
}

int main() {
	int n, m, u, v;
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		cin >> u >> v;
		G[v].push_back(u);
	}
	for (int i = n; i > 0; i--) {
		dfs(i, i);
	}
	for (int i = 1; i <= n; i++) {
		cout << a[i] << ' ';
	}
	return 0;
}

P1113 杂务

题目链接:P1113 杂务 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int ind[10010], t[10010], dp[10010];
vector<int>edge[1000010];
queue<int>q;

int main() {
	int n, x, y;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> x >> t[i];
		while (cin >> y) {
			if (!y) {
				break;
			}
			edge[y].push_back(x);
		
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值