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

Solution (Python):
N,D=map(int,input().split())
F=[tuple(map(int,input().split())) for i in range(N)]

EDGE=[[] for i in range(2*N)]
EDGE_INV=[[] for i in range(2*N)]




for i in range(N):
    x1,y1=F[i]

    for j in range(i,N):
        x2,y2=F[j]

        if abs(x1-x2)<D and i!=j:
            EDGE[i].append(N+j)
            EDGE[j].append(N+i)

            EDGE_INV[N+j].append(i)
            EDGE_INV[N+i].append(j)

        if abs(x1-y2)<D:
            EDGE[i].append(j)
            EDGE[N+j].append(N+i)

            EDGE_INV[j].append(i)
            EDGE_INV[N+i].append(N+j)

        if abs(y1-x2)<D:
            EDGE[N+i].append(N+j)
            EDGE[j].append(i)

            EDGE_INV[N+j].append(N+i)
            EDGE_INV[i].append(j)

        if abs(y1-y2)<D and i!=j:
            EDGE[N+i].append(j)
            EDGE[N+j].append(i)

            EDGE_INV[j].append(N+i)
            EDGE_INV[i].append(N+j)

QUE = list(range(2*N))
check=[0]*(2*N)
TOP_SORT=[]

def dfs(x):
    if check[x]==1:
        return
    check[x]=1
    
    for to in EDGE[x]:
        if check[to]==0:
            dfs(to)

    TOP_SORT.append(x) 
    check[x]=1

while QUE:
    x=QUE.pop()
    dfs(x)

USE=[0]*(2*N)
SCC=[]

def dfs2(x):
    Q=[x]
    USE[x]=1
    ANS=[]

    while Q:
        x=Q.pop()
        ANS.append(x)
        for to in EDGE_INV[x]:
            if USE[to]==0:
                USE[to]=1
                Q.append(to)
    return ANS

for x in TOP_SORT[::-1]:
    if USE[x]==0:
        SCC.append(dfs2(x))


PLACE=[-1]*(2*N)
for i in range(len(SCC)):
    for x in SCC[i]:
        PLACE[x]=i

ANS=[-1]*N
flag=1
for i in range(N):
    if PLACE[i]==PLACE[N+i]:
        flag=0
        break
    
    elif PLACE[i]>PLACE[N+i]:
        ANS[i]=F[i][0]
    else:
        ANS[i]=F[i][1]
    
if flag==0:
    print("No")
else:
    print("Yes")
    for ans in ANS:
        print(ans)

Solution (Python):
N,D=map(int,input().split())
F=[tuple(map(int,input().split())) for i in range(N)]

EDGE=[[] for i in range(2*N)]
EDGE_INV=[[] for i in range(2*N)]




for i in range(N):
    x1,y1=F[i]

    for j in range(i,N):
        x2,y2=F[j]

        if abs(x1-x2)<D and i!=j:
            EDGE[i].append(N+j)
            EDGE[j].append(N+i)

            EDGE_INV[N+j].append(i)
            EDGE_INV[N+i].append(j)

        if abs(x1-y2)<D:
            EDGE[i].append(j)
            EDGE[N+j].append(N+i)

            EDGE_INV[j].append(i)
            EDGE_INV[N+i].append(N+j)

        if abs(y1-x2)<D:
            EDGE[N+i].append(N+j)
            EDGE[j].append(i)

            EDGE_INV[N+j].append(N+i)
            EDGE_INV[i].append(j)

        if abs(y1-y2)<D and i!=j:
            EDGE[N+i].append(j)
            EDGE[N+j].append(i)

            EDGE_INV[j].append(N+i)
            EDGE_INV[i].append(N+j)

QUE = list(range(2*N))
check=[0]*(2*N)
TOP_SORT=[]

def dfs(x):
    if check[x]==1:
        return
    check[x]=1
    
    for to in EDGE[x]:
        if check[to]==0:
            dfs(to)

    TOP_SORT.append(x) 
    check[x]=1

while QUE:
    x=QUE.pop()
    dfs(x)

USE=[0]*(2*N)
SCC=[]

def dfs2(x):
    Q=[x]
    USE[x]=1
    ANS=[]

    while Q:
        x=Q.pop()
        ANS.append(x)
        for to in EDGE_INV[x]:
            if USE[to]==0:
                USE[to]=1
                Q.append(to)
    return ANS

for x in TOP_SORT[::-1]:
    if USE[x]==0:
        SCC.append(dfs2(x))


PLACE=[-1]*(2*N)
for i in range(len(SCC)):
    for x in SCC[i]:
        PLACE[x]=i

ANS=[-1]*N
flag=1
for i in range(N):
    if PLACE[i]==PLACE[N+i]:
        flag=0
        break
    
    elif PLACE[i]>PLACE[N+i]:
        ANS[i]=F[i][0]
    else:
        ANS[i]=F[i][1]
    
if flag==0:
    print("No")
else:
    print("Yes")
    for ans in ANS:
        print(ans)

Solution (Python):
import sys
range = xrange
input = raw_input
 
def find_SCC(coupl):
    SCC, S, P = [], [], []
    depth = [0] * len(coupl)
 
    stack = list(range(len(coupl)))
    while stack:
        node = stack.pop()
        if node < 0:
            d = depth[~node] - 1
            if P[-1] > d:
                SCC.append(S[d:])
                del S[d:], P[-1]
                for node in SCC[-1]:
                    depth[node] = -1
        elif depth[node] > 0:
            while P[-1] > depth[node]:
                P.pop()
        elif depth[node] == 0:
            S.append(node)
            P.append(len(S))
            depth[node] = len(S)
            stack.append(~node)
            stack += coupl[node]
    return SCC[::-1]

class TwoSAT:
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(2 * n)]

    def _imply(self, x, y):
        """ x => y """
        self.graph[x].append(y if y >= 0 else 2 * self.n + y)

    def either(self, x, y):
        """x or y must be True"""
        self._imply(~x, y)
        self._imply(~y, x)

    def set(self, x):
        """x must be True"""
        self._imply(~x, x)

    def solve(self):
        SCC = find_SCC(self.graph)
        
        inSCC = [0] * (2 * self.n)
        for scc_ind, scc in enumerate(SCC):
            for node in scc:
                inSCC[node] = scc_ind
        
        for i in range(self.n):
            if inSCC[i] == inSCC[~i]:
                return False, None
        
        return True, [+(inSCC[i] < inSCC[~i]) for i in range(self.n)]

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
 
n = inp[ii]; ii += 1
d = inp[ii]; ii += 1

sat = TwoSAT(n)

X = inp[ii + 0: ii + 2 * n: 2] 
Y = inp[ii + 1: ii + 2 * n: 2] 
ii += 2 * n

for i in range(n):
    for j in range(i + 1, n):
        if abs(X[i] - X[j]) < d:
            sat.either(i, j)
        
        if abs(Y[i] - Y[j]) < d:
            sat.either(~i, ~j)
        
        if abs(X[i] - Y[j]) < d:
            sat.either(i, ~j)
        
        if abs(Y[i] - X[j]) < d:
            sat.either(~i, j)

exists, solution = sat.solve()

if not exists:
    print 'No'
else:
    print 'Yes'
    print ' '.join(str(X[i] if b else Y[i]) for i, b in enumerate(solution))

Solution (Python):
import sys
range = xrange
input = raw_input
 
def find_SCC(coupl):
    SCC, S, P = [], [], []
    depth = [0] * len(coupl)
 
    stack = list(range(len(coupl)))
    while stack:
        node = stack.pop()
        if node < 0:
            d = depth[~node] - 1
            if P[-1] > d:
                SCC.append(S[d:])
                del S[d:], P[-1]
                for node in SCC[-1]:
                    depth[node] = -1
        elif depth[node] > 0:
            while P[-1] > depth[node]:
                P.pop()
        elif depth[node] == 0:
            S.append(node)
            P.append(len(S))
            depth[node] = len(S)
            stack.append(~node)
            stack += coupl[node]
    return SCC[::-1]

class TwoSAT:
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(2 * n)]

    def _imply(self, x, y):
        self.graph[x].append(y if y >= 0 else 2 * self.n + y)

    def either(self, x, y):
        """either x or y must be True"""
        self._imply(~x, y)
        self._imply(~y, x)

    def set(self, x):
        """x must be True"""
        self._imply(~x, x)

    def solve(self):
        SCC = find_SCC(self.graph)
        
        inSCC = [0] * (2 * self.n)
        for scc_ind, scc in enumerate(SCC):
            for node in scc:
                inSCC[node] = scc_ind
        
        for i in range(self.n):
            if inSCC[i] == inSCC[~i]:
                return False, None
        
        return True, [+(inSCC[i] < inSCC[~i]) for i in range(self.n)]

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
 
n = inp[ii]; ii += 1
d = inp[ii]; ii += 1

sat = TwoSAT(n)

X = inp[ii + 0: ii + 2 * n: 2] 
Y = inp[ii + 1: ii + 2 * n: 2] 
ii += 2 * n

for i in range(n):
    for j in range(i + 1, n):
        
        if abs(X[i] - X[j]) < d:
            sat.either(i, j)
        
        if abs(Y[i] - Y[j]) < d:
            sat.either(~i, ~j)
        
        if abs(X[i] - Y[j]) < d:
            sat.either(i, ~j)
        
        if abs(Y[i] - X[j]) < d:
            sat.either(~i, j)

exists, solution = sat.solve()

if not exists:
    print 'No'
else:
    print 'Yes'
    print ' '.join(str(X[i] if b else Y[i]) for i, b in enumerate(solution))

Solution (Python):



code_two_sat = r"""




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

// >>> AtCoder >>>











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 (
    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






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



// <<< AtCoder <<<

using namespace std;
using namespace atcoder;



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()

Solution (Python):
import types

_atcoder_code = """


__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




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



import sys




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()

Solution (Python):
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, 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:
                
                G[g], g = (i, j + N), g + 1
            if abs(X[i] - Y[j]) < D:
                
                G[g], g = (i, j), g + 1
            if abs(Y[i] - X[j]) < D:
                
                G[g], g = (i + N, j + N), g + 1
            if abs(Y[i] - Y[j]) < D:
                
                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)

Solution (Python):
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, 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:
                
                G[g], g = (i, j + N), g + 1
            if abs(X[i] - Y[j]) < D:
                
                G[g], g = (i, j), g + 1
            if abs(Y[i] - X[j]) < D:
                
                G[g], g = (i + N, j + N), g + 1
            if abs(Y[i] - Y[j]) < D:
                
                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)