Submission #1369498

#TimeUsernameProblemLanguageResultExecution timeMemory
1369498gohchingjaykCoin (NOI24_coin)C++20
100 / 100
281 ms63756 KiB
#pragma GCC optimize("O3,inline")
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
#define int ll

using ii = pair<int, int>;
using iii = pair<int, ii>;

constexpr int MAXN = 200'000 + 5;
constexpr int INF = 1e18 + 5;

vector<ii> adjlist[MAXN];
vector<ii> inedges[MAXN];
vector<int> topoorder;
int idx2topo[MAXN];
bool vis[MAXN];

void dfs(int x) {
	vis[x] = true;
	for (auto [w, ch] : adjlist[x]) if (!vis[ch]) dfs(ch);
	topoorder.emplace_back(x);
}

struct FST {
	
	vector<int> vals;
	int N;
	
	FST(int n, int v): vals(n*2, v), N(n) {}
	
	void point_upd(int p, int v) {
		p += N;
		vals[p] = min(vals[p], v);
		for (; p > 1; p >>= 1) {
			vals[p >> 1] = max(vals[p], vals[p ^ 1]);
		}
	}
	
	int range_qry(int l, int r) {
		int ans = -INF;
		l += N; r += N + 1;
		for (; l < r; l >>= 1, r >>= 1) {
			if (l & 1) ans = max(ans, vals[l++]);
			if (r & 1) ans = max(ans, vals[--r]);
		}
		return ans;
	}
};

signed main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);

	int N, M; cin >> N >> M;
	for (int i = 0; i < M; ++i) {
		int u, v; cin >> u >> v;
		u--, v--;
		adjlist[u].emplace_back(i+1, v);
		inedges[v].emplace_back(i+1, u);
	}
	
	for (int i = 0; i < N; ++i) {
		if (!vis[i]) dfs(i);
	}
	
	for (int i = 0; i < N; ++i) {
		idx2topo[topoorder[i]] = i;
	}
	
	vector<int> ans(N, -1);
	
	FST fst1(N, INF);
	for (int i = 1; i < N; ++i) {
		for (auto [w, ch] : adjlist[topoorder[i]]) {
			fst1.point_upd(idx2topo[ch], w);
		}
		
		ans[topoorder[i]] = max(ans[topoorder[i]], fst1.range_qry(0, i-1));
	}
	
	FST fst2(N, INF);
	for (int i = N-2; i >= 0; --i) {
		for (auto [w, pa] : inedges[topoorder[i]]) {
			fst2.point_upd(idx2topo[pa], w);
		}
		
		ans[topoorder[i]] = max(ans[topoorder[i]], fst2.range_qry(i+1, N-1));
	}
	
	for (int i = 0; i < N; ++i) {
		cout << (ans[i] == INF ? -1ll : ans[i]) << ' ';
	}
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...