Problem:


Score : 100 points

Problem Statement

Consider placing N flags on a line. Flags are numbered through 1 to N.

Flag i can be placed on the coordinate X_i or Y_i.
For any two different flags, the distance between them should be at least D.

Decide whether it is possible to place all N flags. If it is possible, print such a configulation.

Constraints

1 \leq N \leq 1000

0 \leq D \leq 10^9

0 \leq X_i < Y_i \leq 10^9

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N

Output

Print No if it is impossible to place N flags.

If it is possible, print Yes first.
After that, print N lines. i-th line of them should contain the coodinate of flag i.

Sample Input 1

3 2
1 4
2 5
0 6

Sample Output 1

Yes
4
2
0

Sample Input 2

3 3
1 4
2 5
0 6

Sample Output 2

No



Sample input:
3 2
1 4
2 5
0 6


Sample output:
Yes
4
2
0

Submission status: Accepted

Solution code:
# TODO: メモリリーク確認
# TODO: __repr__ を書く

code_two_sat = r"""
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

// 元のライブラリの private を剥がした

// >>> AtCoder >>>

#ifndef ATCODER_TWOSAT_HPP
#define ATCODER_TWOSAT_HPP 1

#ifndef ATCODER_INTERNAL_SCC_HPP
#define ATCODER_INTERNAL_SCC_HPP 1

#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    csr(int n, const std::vector<std::pair<int, E>>& edges)
        : start(n + 1), elist(edges.size()) {
        for (auto e : edges) {
            start[e.first + 1]++;
        }
        for (int i = 1; i <= n; i++) {
            start[i] += start[i - 1];
        }
        auto counter = start;
        for (auto e : edges) {
            elist[counter[e.first]++] = e.second;
        }
    }
};

// Reference:
// R. Tarjan,
// Depth-First Search and Linear Graph Algorithms
struct scc_graph {
  public:
    scc_graph(int n) : _n(n) {}

    int num_vertices() { return _n; }

    void add_edge(int from, int to) { edges.push_back({from, {to}}); }

    // @return pair of (# of scc, scc id)
    std::pair<int, std::vector<int>> scc_ids() {
        auto g = csr<edge>(_n, edges);
        int now_ord = 0, group_num = 0;
        std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);
        visited.reserve(_n);
        auto dfs = [&](auto self, int v) -> void {
            low[v] = ord[v] = now_ord++;
            visited.push_back(v);
            for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                auto to = g.elist[i].to;
                if (ord[to] == -1) {
                    self(self, to);
                    low[v] = std::min(low[v], low[to]);
                } else {
                    low[v] = std::min(low[v], ord[to]);
                }
            }
            if (low[v] == ord[v]) {
                while (true) {
                    int u = visited.back();
                    visited.pop_back();
                    ord[u] = _n;
                    ids[u] = group_num;
                    if (u == v) break;
                }
                group_num++;
            }
        };
        for (int i = 0; i < _n; i++) {
            if (ord[i] == -1) dfs(dfs, i);
        }
        for (auto& x : ids) {
            x = group_num - 1 - x;
        }
        return {group_num, ids};
    }

    std::vector<std::vector<int>> scc() {
        auto ids = scc_ids();
        int group_num = ids.first;
        std::vector<int> counts(group_num);
        for (auto x : ids.second) counts[x]++;
        std::vector<std::vector<int>> groups(ids.first);
        for (int i = 0; i < group_num; i++) {
            groups[i].reserve(counts[i]);
        }
        for (int i = 0; i < _n; i++) {
            groups[ids.second[i]].push_back(i);
        }
        return groups;
    }

  private:
    int _n;
    struct edge {
        int to;
    };
    std::vector<std::pair<int, edge>> edges;
};

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_INTERNAL_SCC_HPP

#include <cassert>
#include <vector>

namespace atcoder {

// Reference:
// B. Aspvall, M. Plass, and R. Tarjan,
// A Linear-Time Algorithm for Testing the Truth of Certain Quantified Boolean
// Formulas
struct two_sat {
  public:
    two_sat() : _n(0), scc(0) {}
    two_sat(int n) : _n(n), _answer(n), scc(2 * n) {}

    void add_clause(int i, bool f, int j, bool g) {
        assert(0 <= i && i < _n);
        assert(0 <= j && j < _n);
        scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0));
        scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0));
    }
    bool satisfiable() {
        auto id = scc.scc_ids().second;
        for (int i = 0; i < _n; i++) {
            if (id[2 * i] == id[2 * i + 1]) return false;
            _answer[i] = id[2 * i] < id[2 * i + 1];
        }
        return true;
    }
    std::vector<bool> answer() { return _answer; }

//  private:
    int _n;
    std::vector<bool> _answer;
    internal::scc_graph scc;
};

}  // namespace atcoder

#endif  // ATCODER_TWOSAT_HPP

// <<< AtCoder <<<

using namespace std;
using namespace atcoder;
#define PARSE_ARGS(types, ...) if(!PyArg_ParseTuple(args, types, __VA_ARGS__)) return NULL


struct TwoSAT{
    PyObject_HEAD
    two_sat* ts;
};


extern PyTypeObject TwoSATType;


// >>> TwoSAT definition >>>

static void TwoSAT_dealloc(TwoSAT* self){
    delete self->ts;
    Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* TwoSAT_new(PyTypeObject* type, PyObject* args, PyObject* kwds){
    return type->tp_alloc(type, 0);
}
static int TwoSAT_init(TwoSAT* self, PyObject* args){
    long n;
    if(!PyArg_ParseTuple(args, "l", &n)) return -1;
    if(n < 0 || n > (long)1e8){
        PyErr_Format(PyExc_IndexError,
            "TwoSAT constructor constraint error (constraint: 0<=n<=1e8, got n=%d)", n);
        return -1;
    }
    self->ts = new two_sat(n);
    return 0;
}
static PyObject* TwoSAT_add_clause(TwoSAT* self, PyObject* args){
    long i, j;
    int f, g;
    PARSE_ARGS("lplp", &i, &f, &j, &g);
    if(i < 0 || i >= self->ts->_n || j < 0 || j >= self->ts->_n){
        PyErr_Format(PyExc_IndexError,
            "TwoSAT add_clause index out of range (n=%d, i=%d, j=%d)", self->ts->_n, i, j);
        return (PyObject*)NULL;
    }
    self->ts->add_clause(i, (bool)f, j, (bool)g);
    Py_RETURN_NONE;
}
static PyObject* TwoSAT_satisfiable(TwoSAT* self, PyObject* args){
    PyObject* res = self->ts->satisfiable() ? Py_True : Py_False;
    return Py_BuildValue("O", res);
}
static PyObject* TwoSAT_answer(TwoSAT* self, PyObject* args){
    const vector<bool>& answer = self->ts->answer();
    const int& n = self->ts->_n;
    PyObject* list = PyList_New(n);
    for(int i = 0; i < n; i++){
        PyList_SET_ITEM(list, i, Py_BuildValue("O", answer[i] ? Py_True : Py_False));
    }
    return list;
}
/*
static PyObject* TwoSAT_repr(PyObject* self){
    PyObject* res = PyUnicode_FromFormat("TwoSAT()");
    return res;
}
*/
static PyMethodDef TwoSAT_methods[] = {
    {"add_clause", (PyCFunction)TwoSAT_add_clause, METH_VARARGS, "Add clause"},
    {"satisfiable", (PyCFunction)TwoSAT_satisfiable, METH_VARARGS, "Check if problem satisfiable"},
    {"answer", (PyCFunction)TwoSAT_answer, METH_VARARGS, "Get answer"},
    {NULL}  /* Sentinel */
};
PyTypeObject TwoSATType = {
    PyObject_HEAD_INIT(NULL)
    "acl_twosat.TwoSAT",                   /*tp_name*/
    sizeof(TwoSAT),                     /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    (destructor)TwoSAT_dealloc,         /*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
    0,                                  /*reserved*/
    0,//TwoSAT_repr,                      /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
    0,                                  /*tp_doc*/
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    0,                                  /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    0,                                  /*tp_iternext*/
    TwoSAT_methods,                     /*tp_methods*/
    0,                                  /*tp_members*/
    0,                                  /*tp_getset*/
    0,                                  /*tp_base*/
    0,                                  /*tp_dict*/
    0,                                  /*tp_descr_get*/
    0,                                  /*tp_descr_set*/
    0,                                  /*tp_dictoffset*/
    (initproc)TwoSAT_init,              /*tp_init*/
    0,                                  /*tp_alloc*/
    TwoSAT_new,                         /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
    0,                                  /*tp_del*/
    0,                                  /*tp_version_tag*/
    0,                                  /*tp_finalize*/
};

// <<< TwoSAT definition <<<


static PyModuleDef acl_twosatmodule = {
    PyModuleDef_HEAD_INIT,
    "acl_twosat",
    NULL,
    -1,
};

PyMODINIT_FUNC PyInit_acl_twosat(void)
{
    PyObject* m;
    if(PyType_Ready(&TwoSATType) < 0) return NULL;

    m = PyModule_Create(&acl_twosatmodule);
    if(m == NULL) return NULL;

    Py_INCREF(&TwoSATType);
    if (PyModule_AddObject(m, "TwoSAT", (PyObject*)&TwoSATType) < 0) {
        Py_DECREF(&TwoSATType);
        Py_DECREF(m);
        return NULL;
    }
    
    return m;
}
"""
code_two_sat_setup = r"""
from distutils.core import setup, Extension
module = Extension(
    "acl_twosat",
    sources=["two_sat.cpp"],
    extra_compile_args=["-O3", "-march=native", "-std=c++14"]
)
setup(
    name="acl_twosat",
    version="0.0.1",
    description="wrapper for atcoder library twosat",
    ext_modules=[module]
)
"""

import os
import sys

if sys.argv[-1] == "ONLINE_JUDGE" or os.getcwd() != "/imojudge/sandbox":
    with open("two_sat.cpp", "w") as f:
        f.write(code_two_sat)
    with open("two_sat_setup.py", "w") as f:
        f.write(code_two_sat_setup)
    os.system(f"{sys.executable} two_sat_setup.py build_ext --inplace")

from acl_twosat import TwoSAT


def main():
    N, D = map(int, input().split())
    XY = [list(map(int, input().split())) for _ in range(N)]
    ts = TwoSAT(N)
    for i, (xi, yi) in enumerate(XY):
        for j, (xj, yj) in enumerate(XY[i+1:], i+1):
            if abs(xi-xj) < D:
                ts.add_clause(i, False, j, False)
            if abs(xi-yj) < D:
                ts.add_clause(i, False, j, True)
            if abs(yi-xj) < D:
                ts.add_clause(i, True, j, False)
            if abs(yi-yj) < D:
                ts.add_clause(i, True, j, True)
    if not ts.satisfiable():
        print("No")
        return
    print("Yes")
    answer = ts.answer()
    for a, (x, y) in zip(answer, XY):
        print(x if a else y)

main()

Submission status: Accepted

Solution code:
import types

_atcoder_code = """
# Python port of AtCoder Library.

__version__ = '0.0.1'
"""

atcoder = types.ModuleType('atcoder')
exec(_atcoder_code, atcoder.__dict__)

_atcoder__scc_code = """
import copy
import sys
import typing


class CSR:
    def __init__(
            self, n: int, edges: typing.List[typing.Tuple[int, int]]) -> None:
        self.start = [0] * (n + 1)
        self.elist = [0] * len(edges)

        for e in edges:
            self.start[e[0] + 1] += 1

        for i in range(1, n + 1):
            self.start[i] += self.start[i - 1]

        counter = copy.deepcopy(self.start)
        for e in edges:
            self.elist[counter[e[0]]] = e[1]
            counter[e[0]] += 1


class SCCGraph:
    '''
    Reference:
    R. Tarjan,
    Depth-First Search and Linear Graph Algorithms
    '''

    def __init__(self, n: int) -> None:
        self._n = n
        self._edges = []

    def num_vertices(self) -> int:
        return self._n

    def add_edge(self, from_vertex: int, to_vertex: int) -> None:
        self._edges.append((from_vertex, to_vertex))

    def scc_ids(self) -> typing.Tuple[int, typing.List[int]]:
        g = CSR(self._n, self._edges)
        now_ord = 0
        group_num = 0
        visited = []
        low = [0] * self._n
        order = [-1] * self._n
        ids = [0] * self._n

        sys.setrecursionlimit(max(self._n + 1000, sys.getrecursionlimit()))

        def dfs(v: int) -> None:
            nonlocal now_ord
            nonlocal group_num
            nonlocal visited
            nonlocal low
            nonlocal order
            nonlocal ids

            low[v] = now_ord
            order[v] = now_ord
            now_ord += 1
            visited.append(v)
            for i in range(g.start[v], g.start[v + 1]):
                to = g.elist[i]
                if order[to] == -1:
                    dfs(to)
                    low[v] = min(low[v], low[to])
                else:
                    low[v] = min(low[v], order[to])

            if low[v] == order[v]:
                while True:
                    u = visited[-1]
                    visited.pop()
                    order[u] = self._n
                    ids[u] = group_num
                    if u == v:
                        break
                group_num += 1

        for i in range(self._n):
            if order[i] == -1:
                dfs(i)

        for i in range(self._n):
            ids[i] = group_num - 1 - ids[i]

        return group_num, ids

    def scc(self) -> typing.List[typing.List[int]]:
        ids = self.scc_ids()
        group_num = ids[0]
        counts = [0] * group_num
        for x in ids[1]:
            counts[x] += 1
        groups = [[] for _ in range(group_num)]
        for i in range(self._n):
            groups[ids[1][i]].append(i)

        return groups
"""

atcoder._scc = types.ModuleType('atcoder._scc')
exec(_atcoder__scc_code, atcoder._scc.__dict__)


_atcoder_twosat_code = """
import typing

# import atcoder._scc


class TwoSAT:
    '''
    Reference:
    B. Aspvall, M. Plass, and R. Tarjan,
    A Linear-Time Algorithm for Testing the Truth of Certain Quantified Boolean
    Formulas
    '''

    def __init__(self, n: int = 0) -> None:
        self._n = n
        self._answer = [False] * n
        self._scc = atcoder._scc.SCCGraph(2 * n)

    def add_clause(self, i: int, f: bool, j: int, g: bool) -> None:
        assert 0 <= i < self._n
        assert 0 <= j < self._n

        self._scc.add_edge(2 * i + (0 if f else 1), 2 * j + (1 if g else 0))
        self._scc.add_edge(2 * j + (0 if g else 1), 2 * i + (1 if f else 0))

    def satisfiable(self) -> bool:
        scc_id = self._scc.scc_ids()[1]
        for i in range(self._n):
            if scc_id[2 * i] == scc_id[2 * i + 1]:
                return False
            self._answer[i] = scc_id[2 * i] < scc_id[2 * i + 1]
        return True

    def answer(self) -> typing.List[bool]:
        return self._answer
"""

atcoder.twosat = types.ModuleType('atcoder.twosat')
exec(_atcoder_twosat_code, atcoder.twosat.__dict__)
atcoder.twosat.__dict__['atcoder'] = atcoder
atcoder.twosat.__dict__['atcoder._scc'] = atcoder._scc
TwoSAT = atcoder.twosat.TwoSAT

# https://atcoder.jp/contests/practice2/tasks/practice2_h

import sys

# from atcoder.twosat import TwoSAT


def main() -> None:
    n, d = map(int, sys.stdin.readline().split())
    x = [0] * n
    y = [0] * n
    for i in range(n):
        x[i], y[i] = map(int, sys.stdin.readline().split())

    two_sat = TwoSAT(n)

    for i in range(n):
        for j in range(i + 1, n):
            if abs(x[i] - x[j]) < d:
                two_sat.add_clause(i, False, j, False)
            if abs(x[i] - y[j]) < d:
                two_sat.add_clause(i, False, j, True)
            if abs(y[i] - x[j]) < d:
                two_sat.add_clause(i, True, j, False)
            if abs(y[i] - y[j]) < d:
                two_sat.add_clause(i, True, j, True)

    if not two_sat.satisfiable():
        print("No")
    else:
        print("Yes")
        answer = two_sat.answer()
        for i in range(n):
            if answer[i]:
                print(x[i])
            else:
                print(y[i])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:, :], i8[:], i8[:], i8[:], i8[:], i8[:], i8, i8, i8, i8),
      cache=True)
def scc_dfs(N, G, idx, low, ord, ids, visited, now_ord, group_num, vis_i, v):
    low[v] = ord[v] = now_ord
    now_ord += 1
    visited[vis_i], vis_i = v, vis_i + 1
    for e in range(idx[v], idx[v + 1]):
        to = G[e, 1]
        if ord[to] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, to)
            low[v] = min(low[v], low[to])
        else:
            low[v] = min(low[v], ord[to])
    if low[v] == ord[v]:
        while True:
            u, vis_i = visited[vis_i - 1], vis_i - 1
            ord[u] = N
            ids[u] = group_num
            if u == v:
                break
        group_num += 1
    return now_ord, group_num, vis_i


@njit((i8, i8[:, :]), cache=True)
def scc(N, G):
    idx = np.searchsorted(G[:, 0], np.arange(N + 1))
    low = np.zeros(N, np.int64)
    ord = np.zeros(N, np.int64) - 1
    now_ord = 0
    group_num = 0
    visited, vis_i = np.empty(N, np.int64), 0
    ids = np.zeros(N, np.int64)
    for v in range(N):
        if ord[v] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, v)
    return group_num, group_num - ids - 1

@njit((i8, i8, i8[:]), cache=True)
def main(N, D, XY):
    # X を True として、two sat に帰着する
    X, Y = XY[::2], XY[1::2]
    G, g = np.empty((4 * N * N, 2), np.int64), 0
    for i in range(N):
        for j in range(N):
            if i == j:
                continue
            if abs(X[i] - X[j]) < D:
                # i True implies j False
                G[g], g = (i, j + N), g + 1
            if abs(X[i] - Y[j]) < D:
                # i True implies j True
                G[g], g = (i, j), g + 1
            if abs(Y[i] - X[j]) < D:
                # i False implies j False
                G[g], g = (i + N, j + N), g + 1
            if abs(Y[i] - Y[j]) < D:
                # i False implies j True
                G[g], g = (i + N, j), g + 1
    G = G[:g]
    G = G[np.argsort(G[:,0])]
    n_comp, comp = scc(N + N, G)
    ans = np.empty(N, np.int64)
    for i in range(N):
        if comp[i] < comp[i + N]:
            ans[i] = Y[i]
        elif comp[i] > comp[i + N]:
            ans[i] = X[i]
        else:
            print('No')
            return
    print('Yes')
    for x in ans:
        print(x)

N, D = map(int, readline().split())
XY = np.array(read().split(), np.int64)

main(N, D, XY)

Submission status: Accepted

Solution code:
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:, :], i8[:], i8[:], i8[:], i8[:], i8[:], i8, i8, i8, i8),
      cache=True)
def scc_dfs(N, G, idx, low, ord, ids, visited, now_ord, group_num, vis_i, v):
    low[v] = ord[v] = now_ord
    now_ord += 1
    visited[vis_i], vis_i = v, vis_i + 1
    for e in range(idx[v], idx[v + 1]):
        to = G[e, 1]
        if ord[to] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, to)
            low[v] = min(low[v], low[to])
        else:
            low[v] = min(low[v], ord[to])
    if low[v] == ord[v]:
        while True:
            u, vis_i = visited[vis_i - 1], vis_i - 1
            ord[u] = N
            ids[u] = group_num
            if u == v:
                break
        group_num += 1
    return now_ord, group_num, vis_i


@njit((i8, i8[:, :]), cache=True)
def scc(N, G):
    idx = np.searchsorted(G[:, 0], np.arange(N + 1))
    low = np.zeros(N, np.int64)
    ord = np.zeros(N, np.int64) - 1
    now_ord = 0
    group_num = 0
    visited, vis_i = np.empty(N, np.int64), 0
    ids = np.zeros(N, np.int64)
    for v in range(N):
        if ord[v] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, v)
    return group_num, group_num - ids - 1

@njit((i8, i8, i8[:]), cache=True)
def main(N, D, XY):
    # X を True として、two sat に帰着する
    X, Y = XY[::2], XY[1::2]
    G, g = np.empty((4 * N * N, 2), np.int64), 0
    for i in range(N):
        for j in range(N):
            if i == j:
                continue
            if abs(X[i] - X[j]) < D:
                # i True implies j False
                G[g], g = (i, j + N), g + 1
            if abs(X[i] - Y[j]) < D:
                # i True implies j True
                G[g], g = (i, j), g + 1
            if abs(Y[i] - X[j]) < D:
                # i False implies j False
                G[g], g = (i + N, j + N), g + 1
            if abs(Y[i] - Y[j]) < D:
                # i False implies j True
                G[g], g = (i + N, j), g + 1
    G = G[:g]
    G = G[np.argsort(G[:,0])]
    n_comp, comp = scc(N + N, G)
    ans = np.empty(N, np.int64)
    for i in range(N):
        if comp[i] < comp[i + N]:
            ans[i] = Y[i]
        elif comp[i] > comp[i + N]:
            ans[i] = X[i]
        else:
            print('No')
            return
    print('Yes')
    for x in ans:
        print(x)

N, D = map(int, readline().split())
XY = np.array(read().split(), np.int64)

main(N, D, XY)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n, d = map(int,input().split())
C = [list(map(int,input().split())) for i in range(n)]

def dfs_numbering(st, M, V, ANS, cnt, v):
    ST = [st]
    while len(ST) > 0:
        i = ST[-1]
        if ANS[i] == -1:
            V[i] = v
            end = 1
            for x in M[i]:
                if V[x] == -1:
                    ST.append(x)
                    end = 0
            if end == 1:
                ST.pop()
                ANS[i] = cnt
                cnt += 1
        else:
            ST.pop()
    return cnt

class scc():  # 有向グラフを強連結成分分解（互いに行き来できる領域ごとに区切る）する。
    def __init__(self, n):  # 頂点数nのグラフを作成
        self.n = n
        self.M = [[] for i in range(n)]
        self.IM = [[] for i in range(n)]

    def add_edge(self, frm, to):  # frm->toの辺を追加
        self.M[frm].append(to)
        self.IM[to].append(frm)

    def scc_list(self):  # 連結成分ごとの頂点リストを返す
        n = self.n
        V = [-1] * n
        ANS = [-1] * n

        cnt = 0
        for i in range(n):
            if V[i] == -1:
                cnt = dfs_numbering(i, self.M, V, ANS, cnt, 0)

        ANS1 = [[ANS[i], i] for i in range(n)]
        ANS1.sort(reverse=True)

        V = [-1] * n
        ANS = [-1] * n
        v = 0
        for i in range(n):
            if V[ANS1[i][1]] == -1:
                dfs_numbering(ANS1[i][1], self.IM, V, ANS, 0, v)
                v += 1

        FANS = [[] for i in range(v)]
        for i in range(n):
            FANS[V[i]].append(i)

        return FANS

class twosat():
    def __init__(self, n):
        self.n = n
        self.S = scc(2*n)
        self.ANS = [True] * n

    def add_clause(self, i, f, j, g):
        fb = (int(f) + 1) % 2
        gb = (int(g) + 1) % 2
        self.S.add_edge(2*i + fb, 2*j + g)
        self.S.add_edge(2*j + gb, 2*i + f)

    def satisfiable(self):
        n = self.n
        sl = self.S.scc_list()
        A = [-1] * (2*n)
        for i in range(len(sl)):
            for j in range(len(sl[i])):
                A[sl[i][j]] = i
        
        for i in range(n):
            if A[2*i] == A[2*i+1]:
                return False
            self.ANS[i] = A[2*i] < A[2*i+1]
        return True

    def answer(self):
        return self.ANS

T = twosat(n)
for i in range(n):
    for j in range(i+1, n):
        # print(i,j)
        for k in range(2):
            for l in range(2):
                if abs(C[i][k] - C[j][l]) < d:
                    # print(i, (k+1)%2, j, (l+1)%2)
                    T.add_clause(i, (k+1)%2, j, (l+1)%2)

sa = T.satisfiable()
if sa:
    print("Yes")
    ANS = T.answer()
    for i in range(n):
        print(C[i][int(ANS[i])])
else:
    print("No")

Submission status: Accepted

Solution code:
class CSR:
    def __init__(self, n: int, edges: list):
        self.start = [0] * (n + 1)
        self.elist = [0] * len(edges)
        for e in edges:
            self.start[e[0] + 1] += 1

        for i in range(1, n + 1):
            self.start[i] += self.start[i - 1]

        counter = self.start[::]  # copy
        for e in edges:
            self.elist[counter[e[0]]] = e[1]
            counter[e[0]] += 1


class SccGraph:
    def __init__(self, n: int = 0):
        self.__n = n
        self.__edges = []

    def __len__(self):
        return self.__n

    def add_edge(self, s: int, t: int):
        assert 0 <= s < self.__n and 0 <= t < self.__n
        self.__edges.append([s, t])

    def scc_ids(self):
        g = CSR(self.__n, self.__edges)
        now_ord = group_num = 0
        visited = []
        low = [0] * self.__n
        order = [-1] * self.__n
        ids = [0] * self.__n
        parent = [-1] * self.__n
        for root in range(self.__n):
            if order[root] == -1:
                stack = [root, root]
                while stack:
                    v = stack.pop()
                    if order[v] == -1:
                        visited.append(v)
                        low[v] = order[v] = now_ord
                        now_ord += 1
                        for i in range(g.start[v], g.start[v + 1]):
                            t = g.elist[i]
                            if order[t] == -1:
                                stack += [t, t]
                                parent[t] = v
                            else:
                                low[v] = min(low[v], order[t])

                    else:
                        if low[v] == order[v]:
                            while True:
                                u = visited.pop()
                                order[u] = self.__n
                                ids[u] = group_num
                                if u == v:
                                    break

                            group_num += 1

                        if parent[v] != -1:
                            low[parent[v]] = min(low[parent[v]], low[v])

        for i, x in enumerate(ids):
            ids[i] = group_num - 1 - x

        return group_num, ids

    def scc(self):
        """
        強連結成分のリストを返す。この時、リストはトポロジカルソートされている
        [[強連結成分のリスト], [強連結成分のリスト], ...]
        """
        group_num, ids = self.scc_ids()
        counts = [0] * group_num
        for x in ids:
            counts[x] += 1

        groups = [[] for _ in range(group_num)]
        for i, x in enumerate(ids):
            groups[x].append(i)

        return groups


class TwoSAT():
    def __init__(self, n):
        self.n = n
        self.res = [0]*self.n
        self.scc = SccGraph(2*n)

    def add_clause(self, i, f, j, g):
        # assert 0 <= i < self.n
        # assert 0 <= j < self.n
        self.scc.add_edge(2*i + (not f), 2*j + g)
        self.scc.add_edge(2*j + (not g), 2*i + f)

    def satisfiable(self):
        """
        条件を足す割当が存在するかどうかを判定する。割当が存在するならばtrue、そうでないならfalseを返す。
        """
        group_num, ids = self.scc.scc_ids()
        for i in range(self.n):
            if ids[2*i] == ids[2*i + 1]: return False
            self.res[i] = (ids[2*i] < ids[2*i+1])
        return True

    def result(self):
        """
        最後に呼んだ satisfiable の、クローズを満たす割当を返す。
        """
        return self.res



#############################################################################

import sys
input = sys.stdin.buffer.readline

N, D = map(int, input().split())
XY = []
for _ in range(N):
    X, Y = map(int, input().split())
    XY.append((X, Y))
ts = TwoSAT(N)
for i in range(N-1):
    x0, y0 = XY[i]
    for j in range(i+1, N):
        x1, y1 = XY[j]
        if abs(x0 - x1) < D:
            ts.add_clause(i, 1, j, 1)
        if abs(x0 - y1) < D:
            ts.add_clause(i, 1, j, 0)
        if abs(y0 - x1) < D:
            ts.add_clause(i, 0, j, 1)
        if abs(y0 - y1) < D:
            ts.add_clause(i, 0, j, 0)

if ts.satisfiable():
    print('Yes')
    print('\n'.join(map(str, (xy[r] for r, xy in zip(ts.result(), XY)))))
else:
    print('No')