Let's construct a graph, and for each tuple we add a directed edge from to with weight . Observe that there cannot be any cycles in this graph, since otherwise no solution would exist. Therefore, we can process the sessions (tuples) in order using topological sort.
Without loss of generality, suppose that the topological sort ordering is so that all edges satisfy . Then, for each directed edge in increasing order of , we set , since the earliest possible date is the later one of and .
Once we process all edges, the resulting are the earliest possible dates with the given edge constraints, and we are done.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;void topo_sorting(vector<vector<pair<int, int>>> &graph, vector<bool> &visited,vector<int> &toposort, int node) {visited[node] = true;for (auto i : graph[node]) {int a, b;tie(a, b) = i;
Java
import java.io.*;import java.util.*;public class timeline {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new FileReader("timeline.in"));PrintWriter pw = new PrintWriter("timeline.out");StringTokenizer st = new StringTokenizer(r.readLine());int N = Integer.parseInt(st.nextToken());int M = Integer.parseInt(st.nextToken());
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!