邻接表+dfs TLE on #8 求助
查看原帖
邻接表+dfs TLE on #8 求助
726139
残阳如血楼主2023/8/21 15:24

rt,代码如下:

#include<iostream>
#include<vector>
#include<cstdio>
#include<array>
#include<queue>
#include<algorithm>
const int MAXN = 1e5 + 10;
namespace IO { // 快读快写
	int len = 0;
	char ibuf[(1 << 20) + 1], *iS, *iT, out[(1 << 26) + 1];
#define gh() (iS==iT?iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT?EOF:*iS++):*iS++)
#define reg register
	inline int read() {
		reg char ch = gh();
		reg int x = 0;
		reg char t = 0;
		while (ch < '0' || ch > '9')   t |= ch == '-', ch = gh();
		while (ch >= '0' && ch <= '9') x = x * 10 + (ch ^ 48), ch = gh();
		return t ? -x : x;
	}
	inline void putc(char ch) {
		out[len++] = ch;
	}
	template<class T>
	inline void write(T x) {
		if (x < 0)putc('-'), x = -x;
		if (x > 9)write(x / 10);
		out[len++] = x % 10 + 48;
	}
	inline void flush() {
		fwrite(out, 1, len, stdout);
		len = 0;
	}
}
using IO::read;
using IO::write;
using IO::flush;
using IO::putc;
std::vector<int> g[MAXN];
std::array<int, MAXN> A;
int N, M;
inline void update(int s) { // 更新能够到达的结点
	std::vector<bool> vis(N + 1);
	std::queue<int> node;
	node.push(s);
	while (!node.empty()) {
		auto u = node.front();
		node.pop();
		if (vis[u]) continue;
		vis[u] = true, A[u] = std::max(A[u], s);
		for (auto v : g[u])
			node.push(v);
	}
}
int main() {
	N = read(), M = read();
	for (reg int i = 1, u, v; i <= M; i++) {
		u = read(), v = read();
		g[v].push_back(u); // 反向建边
	}
	for (reg int u = 1; u <= N; u++) update(u);
	for (reg int i = 1; i <= N; i++) {
		write(A[i]);
		putc(' ');
	}
	flush();
	return 0;
}
2023/8/21 15:24
加载中...