Problema sencillo#12288

Problema sencillo (Editorial)

Author of the problem:

Kostya Denisov (denisov)

Prepared by:

Andrii Kholod (Connect)

Analysis:

Andrii Kholod (Connect)

Solution

Let us consider a directed acyclic graph (DAG). For vertices and we say that u \prec v if there exists a path from to . Any topological ordering of the graph is a linear order that respects this relation: if u \prec v, then must appear earlier than .

From this follows an important fact:

  • the set of all possible topological sorts is completely determined by the reachability relation between vertices;

  • if after removing some edges from the graph the following still holds for all : there exists a path from to if and only if such a path existed in the original graph, then the set of all topological orders remains unchanged.

Thus, the problem essentially asks us to construct the transitive reduction of a DAG: to keep the minimal set of edges such that for every pair of vertices there is a path between them in the new graph if and only if there was one in the original graph.

In other words, an edge must be kept if and only if there is no other path of length from to . If such a path exists, the edge is redundant.

Checking every edge with a separate DFS/BFS would be too slow, so we will handle all edges simultaneously using a topological order and bitmasks.

1. Topological order

We perform a DFS and append each vertex to the array order after exploring all outgoing edges. Then:

[ u v ;; v appears in order earlier than u. ]

If we do not reverse order, it becomes a reverse topological order: all edges point “left”.

Let us create an array pos where pos[x] is the position of vertex in order, and build a new graph :

[ u v in the original graph pos[u] pos[v] in g. ]

Now in graph the start of each edge has a larger index than its end.

2. Blocking vertices in groups of 64 and using bitmasks

Storing a full -bit vector for every vertex is too memory-heavy, so we process vertices in blocks of 64:

  • consider a block of vertices with indices [i, i+63];

  • for each vertex we store a 64-bit value dp[v]: the -th bit is if vertex i+k from this block is reachable from .

For the current block, we iterate vertices in increasing order v = 0, 1, \dots, n-1. Initially:

[ dp[v] =

1 (v - i), if v [i, i+63];

[4pt] 0, otherwise.

]

Then for each edge v \to \texttt{to}, we perform [ dp[v] |= dp[to]. ]

All edges go from larger index to smaller one, so when we process , all dp[to] values for its descendants are already computed. Thus dp[v] eventually contains which vertices of the current block are reachable from .

3. How to determine whether an edge is essential

For each vertex, we pre-sorted its adjacency list g[v] in descending index order. Now while iterating through neighbors:

  • if to does not belong to the current block, we simply update dp[v] |= dp[to];

  • if to is in the current block, let num = to - i be the bit index:

    • if bit num is already set in dp[v], then an alternative path from to to already exists via a neighbor with a greater index (since we iterate in descending order). Thus the edge v \to \texttt{to} is redundant;

    • if the bit is not set, there is no alternative path from to to — so the edge is required.

    After checking, we still do: [ dp[v] |= dp[to]. ]

Why does this capture all redundant edges? In any path [ v p_1 p_2 ...to, ] the vertex indices strictly decrease (the graph is acyclic and edges point left), so p_1 always has a strictly larger index than to. We process such neighbors first, so reachability information is already in dp[v] by the time we check the edge v \to \texttt{to}.

Each edge is checked exactly in the block of its endpoint.

4. Forming the answer

We work with reindexed vertices (according to positions in order), but must output original vertex numbers. Thus, we store all edges (order[v], order[to]) that we decide to keep, then sort them and output them (adding because the input was 1-indexed).

In the resulting graph:

  • every kept edge is minimal: there is no other path between its endpoints;

  • every removed edge was transitive — its reachability can be reproduced through other edges.

Thus, the reachability relation is unchanged, and therefore the set of all topological orders also remains unchanged. The number of edges is minimal because no remaining edge can be removed.

5. Complexity analysis

Let be the number of vertices and the number of edges.

We have about blocks. For each block, we iterate through all vertices and edges once — O(n + m) per block.

Total complexity: [ O((n + m) n64), ] which fits well within limits.

Below is the implementation of the algorithm described:

//#pragma GCC optimize("Ofast", "unroll-loops")
//#pragma GCC target("sse", "sse2", "sse3", "ssse3", "sse4")

#include <bits/stdc++.h>

#define all(a) a.begin(),a.end()
#define len(a) (int)(a.size())
#define mp make_pair
#define pb push_back
#define fi first
#define se second

using namespace std;

typedef pair<int, int> pii;
typedef long long ll;
typedef long double ld;
template<class T>
using vec = vector<T>;

template<typename T>
bool umin(T &a, T b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}
template<typename T>
bool umax(T &a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

const int max_n = 1e5 + 11, inf = 1000111222;

using ull = unsigned long long;

vector<int> edge[max_n], g[max_n];
int used[max_n];
vector<int> order;

void dfs (int v) {
    used[v] = 1;
    for (int to : edge[v]) {
        if (!used[to]) {
            dfs(to);
        }
    }
    order.pb(v);
}

ull dp[max_n];

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    cin >> n >> m;
    for (int i = 0, a, b; i < m; i++) {
        cin >> a >> b;
        --a, --b;
        edge[a].pb(b);
    }
    for (int i = 0; i < n; i++) {
        if (!used[i]) {
            dfs(i);
        }
    }

    vector<int> pos(n);
    for (int i = 0; i < n; i++) {
        pos[order[i]] = i;
    }

    for (int i = 0; i < n; i++) {
        for (int to : edge[i]) {
            g[pos[i]].pb(pos[to]);
        }
    }
    for (int i = 0; i < n; i++) {
        sort(all(g[i]));
        reverse(all(g[i]));
    }

    vector<pii> ans;
    for (int i = 0; i < n; i += 64) {
        for (int v = 0; v < n; v++) {
            dp[v] = 0;
            if (v >= i && v < i + 64) {
                dp[v] |= 1ull << (v - i);
            }
            for (int to : g[v]) {
                if (to >= i && to < i + 64) {
                    int num = to - i;
                    if (!(dp[v] & (1ull << num))) {
                        ans.pb({order[v], order[to]});
                    }
                }
                dp[v] |= dp[to];
            }
        }
    }

    sort(all(ans));
    cout << len(ans) << '\n';
    for (auto &i : ans) {
        cout << i.first + 1 << ' ' << i.second + 1 << '\n';
    }
}