#269.查找文献求调and#270.图的遍历求调

CPP 刷题王 2023-03-18 20:41:50 2023-03-18 21:00:20 0

本蒟蒻dfs没做出来就没写bfs

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int h[N], ne[N], e[N], idx, n, m;
int ans[N];
void add(int a, int b) {
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int t) {
	cout << t << ' ';
	for (int i = h[t]; i != -1; i = ne[i]) {
		if (!ans[i]) {
			ans[i] = 1;
			dfs(i);
		}
	}
}
int main() {
	memset(h, -1, sizeof(h));
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y;
		cin >> x >> y;
		add(x, y);
	}
	ans[1] = 1;
	dfs(1);
}

270:

#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], ne[N], idx, n, m;
int ans[N];
void add(int a, int b) {
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u, int v) {
	ans[u] = v;
	for (int i = h[u]; i != -1; i = ne[i])
		if (!ans[i])
			dfs(i, v);
}
int main() {
	memset(h, -1, sizeof(h));
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int a, b;
		cin >> a >> b;
		add(b, a);
	}
	for (int i = n; i >= 0; i--)
		if (!ans[i])
			dfs(i, i);
	for (int i = 1; i <= n; i++)
		cout << ans[i] << ' ';
	return 0;
}

话说为啥vector就能AC

{{ vote && vote.total.up }}

共 3 条回复

CPP 刷题王

CPP 刷题王

?

root 站长

1