#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
#include <random>
#include <stack>
#include <iomanip>
#include <ctime>
#include <limits.h>
#include <chrono>

#define fast                          \
    ios_base::sync_with_stdio(false); \
    cin.tie(0);                       \
    cout.tie(0);

#define ll long long
#define ld long double

#define pb push_back
#define ins insert
#define er erase

#define f(i, a, b) for (int i = a; i < b; ++i)
#define rf(i, a, b) for (int i = a; i >= b; --i)
#define cmax(a, b) a = max(a, b)
#define cmin(a, b) a = min(a, b)
#define cadd(a, b) a = add(a, b)
#define csub(a, b) a = subt(a, b)
#define cmul(a, b) a = mult(a, b)
#define mem(a, b) memset(a, b, sizeof(a))

#define vi vector<int>
#define vst vector<string>
#define vpii vector<pii>
#define sz(a) (int)(a).size()

#define all(v) v.begin(), v.end()
#define lb lower_bound
#define ub upper_bound
#define mxe max_element
#define mne min_element

#define srt(v) sort(all(v))
#define rsrt(v) sort(v.rbegin(), v.rend())

#define pii pair<int, int>
#define ff first
#define ss second

#define bs bitset
#define bpc(a) __builtin_popcount(a)
#define prec(a) fixed << setprecision(a)

#define mii map<int, int>
#define umii unordered_map<int, int>

#define si set<int>
#define usi unordered_set<int>
#define spii set<pii>

#define dbg(a, st, end)                   \
    f(i, st, end + 1) cerr << a[i] << sp; \
    cerr << nl;
#define pnt(a, st, end)                   \
    f(i, st, end + 1) cout << a[i] << sp; \
    cout << nl;
#define dbgc(a)          \
    for (auto y : a)     \
        cerr << y << sp; \
    cerr << nl;
#define dbgm(a)                            \
    for (auto y : a)                       \
        cerr << y.ff << "," << y.ss << sp; \
    cerr << nl;

#define trace(a) cerr << a << nl;
#define trace2(a, b) cerr << a << sp << b << nl;
#define trace3(a, b, c) cerr << a << sp << b << sp << c << nl;
#define trace4(a, b, c, d) cerr << a << sp << b << sp << c << sp << d << nl;

#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) ((a)*1ll * (b)) / gcd(a, b)

#define nl "\n"
#define sp " "

using namespace std;
using namespace std::chrono;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

#define ordered_set tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update>
#define ok order_of_key
#define fo find_by_order

ll md = 1000000007;
ld pi = 3.141592653;
//ll md = 998244353;

ll pw(ll a, ll b)
{
    ll c = 1, m = a;
    while (b)
    {
        if (b & 1)
            c = (c * m);
        m = (m * m);
        b /= 2;
    }
    return c;
}

ll pwmd(ll a, ll b)
{
    ll c = 1, m = a;
    while (b)
    {
        if (b & 1)
            c = (c * m) % md;
        m = (m * m) % md;
        b /= 2;
    }
    return c;
}

ll modinv(ll n)
{
    return pwmd(n, md - 2);
}

ll my_ceil(ll a, ll b)
{
    if (a % b == 0)
        return a / b;
    return a / b + 1;
}

ll nc2(ll n)
{
    return (1ll * n * (n - 1)) / 2;
}

ll nsum(ll n)
{
    return (1ll * n * (n + 1)) / 2;
}

int my_log(ll n, int b)
{
    ll i = 1;
    int ans = 0;
    while (1)
    {
        if (i > n / b)
            break;
        i *= b;
        ans++;
    }
    return ans;
}

inline int nc()
{
    static char buf[100000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++;
}

inline int read()
{
    int ret = 0;
    bool f = 0;
    char ch = nc();
    while (ch > '9' || ch < '0')
        f ^= ch == '-', ch = nc();
    while (ch <= '9' && ch >= '0')
        ret = ret * 10 + ch - '0', ch = nc();
    return f ? -ret : ret;
}

inline int randint(int l, int r)
{
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    return uniform_int_distribution<int>(l, r)(rng);
}

inline ll randll(ll l, ll r)
{
    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
    return uniform_int_distribution<ll>(l, r)(rng);
}

int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};

inline ll add(ll a, ll b) { return (((a >= md) ? a % md : a) + ((b >= md) ? b % md : b) + md) % md; }
inline ll subt(ll a, ll b) { return (a - b + md) % md; }
inline ll mult(ll a, ll b) { return (1ll * ((a >= md) ? a % md : a) * ((b >= md) ? b % md : b)) % md; }

inline int manhatten(pii p1, pii p2) { return abs(p1.ff - p2.ff) + abs(p1.ss - p2.ss); }

inline bool kthbit(ll n, int k) { return (n >> k) & 1; }
inline ll setkthbit(ll n, int k) { return n | (1ll << k); }
inline ll unsetkthbit(ll n, int k) { return n & ~(1ll << k); }
inline ll flipkthbit(ll n, int k) { return n ^ (1ll << k); }

#define int long long //UNCOMMENT IF NEEDED
#define UNAGI

/*
    You have to stop the Q-Tip when there's resistance!
                                - Chandler Bing, S02E01
*/

const int N = 505;

vi adj[N];
int n;

bool topo(int spNode)
{
    int indeg[n + 1];
    mem(indeg, 0);
    f(i, 1, 1 + n) for (auto y : adj[i]) indeg[y]++;
    //dbgc(indeg);
    set<pair<bool, pii>> nodes;
    f(i, 1, 1 + n) nodes.ins({indeg[i], {i != spNode, i}});
    int surplus = 0, c = 0;
    while (!nodes.empty())
    {
        auto p = *nodes.begin();
        surplus += p.ff; //trace(p.ss.ss);
        nodes.er(nodes.begin());
        for (auto y : adj[p.ss.ss])
        {
            if (nodes.find({indeg[y], {y != spNode, y}}) == nodes.end())
                continue;
            nodes.er({indeg[y], {y != spNode, y}});
            indeg[y]--;
            nodes.ins({indeg[y], {y != spNode, y}});
        }
    }
    //trace2(spNode,surplus);
    return surplus < 2;
}

bool solve()
{
    int indeg[n + 1];
    mem(indeg, 0);
    f(i, 1, 1 + n) for (auto y : adj[i]) indeg[y]++;
    //dbgc(indeg);
    spii nodes;
    f(i, 1, 1 + n) nodes.ins({indeg[i], i});
    vi candidates;
    while (!nodes.empty())
    {
        pii p = *nodes.begin();
        if (p.ff)
        {
            for (auto y : nodes)
                if (y.ff == p.ff)
                    candidates.pb(y.ss);
            break;
        }
        nodes.er(p);
        for (auto y : adj[p.ss])
        {
            nodes.er({indeg[y], y});
            indeg[y]--;
            nodes.ins({indeg[y], y});
        }
    } //dbgc(candidates);
    bool ans = 0;
    for (auto y : candidates)
        ans |= topo(y);
    return ans;
}

int32_t main()
{
    fast;

#ifndef UNAGI
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int h, e, m, y, k;
    int x, q, l, r, c;

    string s, t;

    auto start = high_resolution_clock::now();

    int tcnt = 0;

    int tests = 1;
    //pre();
    //cin >> tests;

    while (tests--)
    {
        //cout << "Case #" << ++tcnt << ": ";

        cin >> n >> m;
        while (m--)
            cin >> l >> r, adj[l].pb(r);
        cout << (solve() ? "YES" : "NO");

        // RESTORE SEGTREE SIZE
    }
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cerr << "Time taken: "
         << duration.count() / 1000000.0 << "seconds" << nl;
    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m, cur = 1, vis[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p) {
    vis[v] = cur;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to] == cur) {
            to_del.pb(mp(v, to));
            return to;
        }
        if (vis[to] < cur && vis[to] != 0)
            continue;
        int res = dfs(to, v);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    return -1;
}

bool no_cycles(int v) {
    vis[v] = cur;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to] == cur)
            return false;
        if (vis[to] < cur && vis[to] != 0)
            continue;
        if (!no_cycles(to))
            return false;
    }
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    for (int j = 0; j < n; j++) {
        if (vis[j] != 0)
            continue;
        if(dfs(j, -1) == -2)
            break;
        cur++;
    }

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = 0;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        bool good = true;
        cur = 1;
        for (int j = 0; j < n; j++) {
            if (vis[j] == 0 && !no_cycles(j)) {
                good = false;
                break;
            }
            cur++;
        }
        if (good) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N], gr[N];
int order[N], revp[N], bal[N], comp[N], col[N], col1 = 0, n, m, cur = 0, cycle_col = 0;
int col2 = 0, gd = -1;
pii ed[N * N];
bool vis[N];

void top_sort(int v) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to])
            continue;
        top_sort(to);
    }
    order[cur] = v;
    revp[v] = cur;
    cur++;
}

void dfs(int v) {
    vis[v] = true;
    comp[v] = cur;
    col[cur]++;

    for (int i = 0; i < gr[v].size(); i++) {
        int to = gr[v][i];
        if (vis[to])
            continue;
        dfs(to);
    }
}

void cycle(int v) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (comp[to] != gd)
            continue;
        if (vis[to]) {
            cycle_col++;
            bal[to]++;
            bal[v]--;
            continue;
        }
        cycle(to);
    }
}

void bal_dfs(int v, int curbal) {
    vis[v] = true;
    curbal += bal[v];
    if (curbal == cycle_col) {
        cout << "YES";
        exit(0);
    }
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (comp[to] != gd)
            continue;
        if (vis[to]) {
            continue;
        }
        bal_dfs(to, curbal);
    }
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        cin >> ed[i].fs >> ed[i].sc;
        ed[i].fs--, ed[i].sc--;
        g[ed[i].fs].pb(ed[i].sc);
        gr[ed[i].sc].pb(ed[i].fs);
    }

    for (int i = 0; i < n; i++) {
        if (vis[i])
            continue;
        top_sort(i);
    }

    reverse(order, order + n);
    cur = 0;
    for (int i = 0; i < n; i++)
        vis[i] = false;

    for (int i = 0; i < n; i++) {
        int v = order[i];
        if (vis[v])
            continue;
        dfs(v);
        cur++;
    }

    for (int i = 0; i < cur; i++) {
        if (col[i] > 1) {
            col2++;
            gd = i;
        }
    }
    if (col2 > 1) {
        cout << "NO";
        return 0;
    }
    if (col2 == 0) {
        cout << "NO";
        return 0;
    }

    for (int i = 0; i < n; i++) {
        vis[i] = false;
        random_shuffle(g[i].begin(), g[i].end());
    }

    for (int i = 0; i < n; i++) {
        if (comp[i] != gd)
            continue;
        cycle(i);
        for (int i = 0; i < n; i++)
            vis[i] = false;
        bal_dfs(i, 0);
        cout << "NO";
        return 0;
    }

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m, cur = 1, vis[N], tin[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p, int t) {
    vis[v] = cur;
    tin[v] = t;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to] == cur) {
            if(tin[to] < tin[v]) {
                to_del.pb(mp(v, to));
                return to;
            }
            else
                continue;
        }

        if (vis[to] < cur && vis[to] != 0)
            continue;
        int res = dfs(to, v, t + 1);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    return -1;
}

bool no_cycles(int v, int t) {
    vis[v] = cur;
    tin[v] = t;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to] == cur) {
            if (tin[to] < tin[v])
                return false;
            else
                continue;
        }
        if (vis[to] < cur && vis[to] != 0)
            continue;
        if (!no_cycles(to, t + 1))
            return false;
    }
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    for (int j = 0; j < n; j++) {
        if (vis[j] != 0)
            continue;
        if(dfs(j, -1, 1) == -2)
            break;
        cur++;
    }

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = 0, tin[j] = 0;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        //cout << to_del[i].fs << " " << to_del[i].sc << endl;
        bool good = true;
        cur = 1;
        for (int j = 0; j < n; j++) {
            if (vis[j] == 0 && !no_cycles(j, 1)) {
                good = false;
                break;
            }
            cur++;
        }
        if (good) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m, cur = 1, vis[N], tin[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p, int t) {
    vis[v] = cur;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to] == cur) {
            if(tin[to] == INF) {
                to_del.pb(mp(v, to));
                return to;
            }
            else
                continue;
        }

        if (vis[to] < cur && vis[to] != 0)
            continue;
        int res = dfs(to, v, t + 1000);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    tin[v] = t;
    return -1;
}

bool no_cycles(int v, int t) {
    vis[v] = cur;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to] == cur) {
            if (tin[to] == INF)
                return false;
            else
                continue;
        }
        if (vis[to] < cur && vis[to] != 0)
            continue;
        if (!no_cycles(to, t + 1))
            return false;
    }
    tin[v] = t;
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    for (int j = 0; j < n; j++)
        tin[j] = INF;
    for (int j = 0; j < n; j++) {
        if (vis[j] != 0)
            continue;
        if(dfs(j, -1, 1) == -2)
            break;
        if (to_del.size() > 0)
            break;
        cur++;
    }

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = 0, tin[j] = INF;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        //cout << to_del[i].fs << " " << to_del[i].sc << endl;
        bool good = true;
        cur = 1;
        for (int j = 0; j < n; j++) {
            if (vis[j] == 0 && !no_cycles(j, 1)) {
                good = false;
                break;
            }
            cur++;
        }
        if (good) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m;
bool vis[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to]) {
            to_del.pb(mp(v, to));
            return to;
        }
        int res = dfs(to, v);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    return -1;
}

bool no_cycles(int v) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to])
            return false;
        if (!no_cycles(to))
            return false;
    }
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    dfs(0, -1);

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = false;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        if (no_cycles(0)) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m, cur = 1, vis[N], tin[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p, int t) {
    vis[v] = cur;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to] == cur) {
            if(tin[to] == INF) {
                to_del.pb(mp(v, to));
                return to;
            }
            else
                continue;
        }

        if (vis[to] < cur && vis[to] != 0)
            continue;
        int res = dfs(to, v, t + 1000);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    tin[v] = t;
    return -1;
}

bool no_cycles(int v, int t) {
    vis[v] = cur;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to] == cur) {
            if (tin[to] == INF)
                return false;
            else
                continue;
        }
        if (vis[to] < cur && vis[to] != 0)
            continue;
        if (!no_cycles(to, t + 1))
            return false;
    }
    tin[v] = t;
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    for (int j = 0; j < n; j++)
        tin[j] = INF;
    for (int j = 0; j < n; j++) {
        if (vis[j] != 0)
            continue;
        if(dfs(j, -1, 1) == -2)
            break;
        if (to_del.size() > 0)
            break;
        cur++;
    }

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = 0, tin[j] = INF;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        cout << to_del[i].fs << " " << to_del[i].sc << endl;
        bool good = true;
        cur = 1;
        for (int j = 0; j < n; j++) {
            if (vis[j] == 0 && !no_cycles(j, 1)) {
                good = false;
                break;
            }
            cur++;
        }
        if (good) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N], gr[N];
int order[N], revp[N], bal[N], comp[N], col[N], col1 = 0, n, m, cur = 0, cycle_col = 0;
int col2 = 0, gd = -1;
pii ed[N * N];
bool vis[N];

void top_sort(int v) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to])
            continue;
        top_sort(to);
    }
    order[cur] = v;
    revp[v] = cur;
    cur++;
}

void dfs(int v) {
    vis[v] = true;
    comp[v] = cur;
    col[cur]++;

    for (int i = 0; i < gr[v].size(); i++) {
        int to = gr[v][i];
        if (vis[to])
            continue;
        dfs(to);
    }
}

void cycle(int v) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (comp[to] != gd)
            continue;
        if (vis[to]) {
            cycle_col++;
            bal[to]++;
            bal[v]--;
            continue;
        }
        cycle(to);
    }
}

void bal_dfs(int v, int curbal) {
    vis[v] = true;
    curbal += bal[v];
    if (curbal == cycle_col) {
        cout << "YES";
        exit(0);
    }
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (comp[to] != gd)
            continue;
        if (vis[to]) {
            continue;
        }
        bal_dfs(to, curbal);
    }
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        cin >> ed[i].fs >> ed[i].sc;
        ed[i].fs--, ed[i].sc--;
        g[ed[i].fs].pb(ed[i].sc);
        gr[ed[i].sc].pb(ed[i].fs);
    }

    for (int i = 0; i < n; i++) {
        if (vis[i])
            continue;
        top_sort(i);
    }

    reverse(order, order + n);
    cur = 0;
    for (int i = 0; i < n; i++)
        vis[i] = false;

    for (int i = 0; i < n; i++) {
        int v = order[i];
        if (vis[v])
            continue;
        dfs(v);
        cur++;
    }

    for (int i = 0; i < cur; i++) {
        if (col[i] > 1) {
            col2++;
            gd = i;
        }
    }
    if (col2 > 1) {
        cout << "NO";
        return 0;
    }
    if (col2 == 0) {
        cout << "NO";
        return 0;
    }

    for (int i = 0; i < n; i++)
        vis[i] = false;

    for (int i = 0; i < n; i++) {
        if (comp[i] != gd)
            continue;
        cycle(i);
        for (int i = 0; i < n; i++)
            vis[i] = false;
        bal_dfs(i, 0);
        cout << "NO";
        return 0;
    }

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m;
bool vis[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to]) {
            to_del.pb(mp(v, to));
            return to;
        }
        int res = dfs(to, v);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    return -1;
}

bool no_cycles(int v) {
    vis[v] = true;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to])
            return false;
        if (!no_cycles(to))
            return false;
    }
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    for (int j = 0; j < n; j++) {
        if (vis[j])
            continue;
        if(dfs(j, -1) == -2)
            break;
    }

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = false;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        bool good = true;
        for (int j = 0; j < n; j++) {
            if (!vis[j] && !no_cycles(j)) {
                good = false;
                break;
            }
        }
        if (good) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <bits/stdc++.h>

/*
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("-O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define mp make_pair
#define ll long long
#define ld long double
#define pb push_back
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fs first
#define sc second
#define getfiles ifstream cin("input.txt"); ofstream cout("output.txt");
#define endl '\n'
#define con continue
#define pii pair<int, int>
#define all(x) x.begin(), x.end()

const int INF = 2000000005;
const ll BIG_INF = 2000000000000000005;
const int mod = 1000000007;
const int P = 31;
const ld PI = 3.141592653589793238462643;
const double eps = 1e-9;

using namespace std;

vector< pair<int, int> > dir = {
    {
        -1, 0
    },
    {
        0, 1
    },
    {
        1, 0
    },
    {
        0, -1
    }
};

bool valid(int x, int y, int n, int m) {
    return x >= 0 && y >= 0 && x < n && y < m;
}

mt19937 rng(1999999973);

const int N = 505;
vector<int> g[N];
int n, m, cur = 1, vis[N], tin[N];
map<pii, bool> del;
vector<pii> to_del;

int dfs(int v, int p, int t) {
    vis[v] = cur;
    tin[v] = t;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (vis[to] == cur && tin[to] < tin[v]) {
            to_del.pb(mp(v, to));
            return to;
        }
        if (vis[to] < cur && vis[to] != 0)
            continue;
        int res = dfs(to, v, t + 1);
        if (res == -2)
            return -2;
        if (res != -1) {
            to_del.pb(mp(v, to));
            if (v == res)
                return -2;
            else
                return res;
        }
    }
    return -1;
}

bool no_cycles(int v, int t) {
    vis[v] = cur;
    tin[v] = t;
    for (int i = 0; i < g[v].size(); i++) {
        int to = g[v][i];
        if (del[mp(v, to)])
            continue;
        if (vis[to] == cur && tin[to] < tin[v])
            return false;
        if (vis[to] < cur && vis[to] != 0)
            continue;
        if (!no_cycles(to, t + 1))
            return false;
    }
    return true;
}

signed main() {
    fast_io;

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].pb(v);
    }
    for (int j = 0; j < n; j++) {
        if (vis[j] != 0)
            continue;
        if(dfs(j, -1, 1) == -2)
            break;
        cur++;
    }

    if (to_del.empty()) {
        cout << "YES";
        return 0;
    }

    for (int i = 0; i < to_del.size(); i++) {
        for (int j = 0; j < n; j++)
            vis[j] = 0, tin[j] = 0;
        del[mp(to_del[i].fs, to_del[i].sc)] = true;
        //cout << to_del[i].fs << " " << to_del[i].sc << endl;
        bool good = true;
        cur = 1;
        for (int j = 0; j < n; j++) {
            if (vis[j] == 0 && !no_cycles(j, 1)) {
                good = false;
                break;
            }
            cur++;
        }
        if (good) {
            cout << "YES";
            return 0;
        }
        del[mp(to_del[i].fs, to_del[i].sc)] = false;
    }
    cout << "NO";

    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

int visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{

    bool ok = true;
    visited3[pos] = 2;
    for (int nxt : edges[pos])
    {
        if (pos == L and nxt == R)
        {
            continue;
        }
        if (visited3[nxt] == 1)
        {
            continue;
        }
        if (visited3[nxt] == 2)
        {
            return false;
        }
        ok &= dfs1(nxt, L, R);
    }
    visited3[pos] = 1;
    return ok;
}

bool asyclic(int root, int L, int R)
{

    memset(visited3, 0, sizeof(visited3));
    bool ok = true;
    for (int i = 0; i < N; i++)
    {
        if (visited3[i] == 0)
        {
            ok &= dfs1(i, L, R);
        }
    }
    return ok;
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[0], cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

bool visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{
    if (visited3[pos])
    {
        return false;
    }
    visited3[pos] = true;
    bool ok = true;
    for (int nxt : edges[pos])
    {
        if (pos == L and nxt == R)
        {
            continue;
        }

        ok &= dfs1(nxt, L, R);
    }
    return ok;
}

bool asyclic(int root, int L, int R)
{

    memset(visited3, false, sizeof(visited3));
    return dfs1(root, L, R);
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[0], cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

bool visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{
    if (visited3[pos])
    {
        return false;
    }
    visited3[pos] = true;
    bool ok = true;
    for (int nxt : edges[pos])
    {
        if (pos == L and nxt == R)
        {
            continue;
        }
        if (pos == R and nxt == L){
            continue;
        }
        ok &= dfs1(nxt, L, R);
    }
    return ok;
}

bool asyclic(int L, int R)
{
    int root = L;
    memset(visited3, false, sizeof(visited3));
    return dfs1(root, L, R);
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

int visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{
    if (visited3[pos] == 2)
    {
        return false;
    }
    visited3[pos] = 2;
    bool ok = true;
    for (int nxt : edges[pos])
    {
        if (pos == L and nxt == R)
        {
            continue;
        }
        if (visited3[pos] == 1)
        {
            continue;
        }
        if (visited3[pos] == 2)
        {
            return false;
        }
        ok &= dfs1(nxt, L, R);
    }
    visited3[pos] = 1;
    return ok;
}

bool asyclic(int root, int L, int R)
{

    memset(visited3, 0, sizeof(visited3));
    return dfs1(root, L, R);
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[0], cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

bool visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{
    if (visited3[pos])
    {
        return false;
    }
    visited3[pos] = true;
    bool ok = true;
    for (int nxt : edges[pos])
    {
        if (pos == L and nxt == R)
        {
            continue;
        }
        if (pos == R and nxt == L){
            continue;
        }
        ok &= dfs1(nxt, L, R);
    }
    return ok;
}

bool asyclic(int root, int L, int R)
{

    memset(visited3, false, sizeof(visited3));
    return dfs1(root, L, R);
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[0], cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

bool asyclic(int L, int R)
{
    int in[MAX_N] = {};
    for (int i = 0; i < N; i++)
    {
        for (int e : edges[i])
        {
            if (L == i and R == e)
            {
                continue;
            }
            in[e]++;
        }
    }
    queue<int> Q;
    for (int i = 0; i < N; i++)
    {
        if (in[i] == 0)
        {
            Q.push(i);
        }
    }
    int left = N;
    while (not Q.empty())
    {
        int cur = Q.front();
        left--;
        Q.pop();
        for (int e : edges[cur])
        {
            if (L == cur and R == e)
            {
                continue;
            }
            in[e]--;
            if (in[e] == 0)
            {
                Q.push(e);
            }
        }
    }
    return left == 0;
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

int visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{

    bool ok = true;
    visited3[pos] = 2;
    for (int nxt : edges[pos])
    {
        if (pos == L and nxt == R)
        {
            continue;
        }
        if (visited3[nxt] == 1)
        {
            continue;
        }
        if (visited3[nxt] == 2)
        {
            return false;
        }
        ok &= dfs1(nxt, L, R);
    }
    visited3[pos] = 1;
    return ok;
}

bool asyclic(int root, int L, int R)
{

    memset(visited3, 0, sizeof(visited3));
    bool ok = dfs1(root, L, R);
    // for (int i = 0; i < N; i++)
    // {
    //     if (visited3[i] == 0)
    //     {
    //         ok &= dfs1(i, L, R);
    //     }
    // }
    return ok;
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[0], cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const int INF = 1 << 29;
const ll LL_INF = 1LL << 60;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 510;
vector<int> edges[MAX_N];
int visited1[MAX_N];
int visited2[MAX_N];
int N, M;

void dfs(int cur, vector<int> &V, vector<int> &cand)
{
    if (visited2[cur])
    {
        return;
    }
    visited1[cur]++;
    if (visited1[cur] >= 2)
    {
        for (int i = V.size() - 1; i >= 0; i--)
        {
            cand.push_back(V[i]);
            if (V[i] == cur)
            {
                break;
            }
        }
        reverse(cand.begin(), cand.end());
        cand.push_back(cur);
        return;
    }

    V.push_back(cur);
    for (const auto &nxt : edges[cur])
    {
        if (cand.empty())
        {
            dfs(nxt, V, cand);
        }
    }

    V.pop_back();
    visited2[cur]++;
}

bool visited3[MAX_N];

bool dfs1(int pos, const int L, const int R)
{
    if (visited3[pos])
    {
        return false;
    }
    visited3[pos] = true;
    bool ok = true;
    for (int nxt : edges[pos])
    {
        if (L == pos and R == nxt)
        {
            continue;
        }
        ok &= dfs1(nxt, L, R);
    }
    return ok;
}

bool asyclic(int L, int R)
{
    int root = L;
    memset(visited3, false, sizeof(visited3));
    return dfs1(root, L, R);
}

int main()
{
    cin >> N >> M;
    for (int i = 0; i < M; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        edges[x].push_back(y);
    }

    vector<int> cand;
    for (int i = 0; i < N; i++)
    {

        if (visited2[i] == 0 and cand.empty())
        {
            memset(visited1, 0, sizeof(visited1));
            vector<int> V;
            dfs(i, V, cand);
        }
    }
    if (cand.empty())
    {
        cout << "YES" << endl;
        return 0;
    }

    for (int i = 0; i < cand.size() - 1; i++)
    {
        if (asyclic(cand[i], cand[i + 1]))
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;
    return 0;
}


/* Author : Aaryan Srivastava ^__^ */
#include <bits/stdc++.h>
#include <random>
#include <chrono>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define pb push_back
#define popb pop_back
#define mt make_tuple
#define eb emplace_back
#define mp make_pair
#define ff first
#define ss second
#define ull unsigned long long
#define pii pair<int, int>
#define piii pair<int,pii>
#define beg begin
#define rep(i,n) for(int (i) = 0 ; i < (n) ; i++)
#define repA(i,x,y) for(int i = (x) ; i <= (y) ; i++)
#define repD(i,x,y) for(int i = (x) ; i >= (y) ; i--)
#define all(c) (c).begin(),(c).end()
#define fill(a,val) memset(a,val,sizeof(a))
#define Randomize mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define int ll
using ll = long long;
const int N = 3*1e5 +5 ;
const int mod = 1e9 + 7 ;
const int inf = 1e18 ;
const int SZ = 101 ;
const double eps = 1e-9 ;
using namespace __gnu_pbds;
using namespace std;
using ordered_set =  tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ;

#ifdef AaryanS
#define mycout cout
#define mycerr cerr
#endif

#ifndef AaryanS
#define mycout if(false) cout
#define mycerr if(false) cerr
#endif

vector<int> g[501], gr[501];
vector<int> used;
vector<int> chc;
int par[501] , fl ;

bool dfs(int u , int p = -1){
  par[u] = p;
  used[u] = 1;
  if(fl) return true ;
  for(auto it : g[u]){
    if(used[it] == 1){
      int cur = u ;
      // cout << u << " " << it << "\n";
      // cout << cur << " " ;
      while(cur != -1){
        chc.pb(cur);
        cur = par[cur];
      }
      // cout << u << "\n" ;
      chc.pb(u);
      reverse(all(chc));
      return (fl = true);
    }else if(used[it] == 0){
      if(dfs(it , u)) return (fl = true);
    }
  }
  used[u] = 2;
  return false;
}

bool dfs3(int v , vector<int> g[501]){
  used[v] = 1 ;
  bool ans = true;
  for(auto it : g[v]){
    if(used[it] == 1) return false;
    if(used[it] == 0)
      ans &= dfs3(it , g);
  }
  used[v] = 2;
  return ans ;
}

bool GO(int x, int y, int n){
  vector<int> GG[n];
  rep(i , n){
    for(auto it : g[i]){
      if(i == x && it == y) continue ;
      GG[i].pb(it);
    }
  }
  bool ans = true;
  used.assign(n , 0);
  rep(i ,n) if(!used[i]) ans &= dfs3(i , GG);
  return ans ;
}

void solve()
{
  fill(par , -1);
  int n , m ;
  cin >> n >> m ;
  rep(i , m) {
      int a, b;
      cin >> a >> b;
      --a , --b;
      g[a].push_back (b);
  }
  used.assign(n , 0);
  rep(i , n) if(!used[i]) dfs(i);
  if(chc.empty()){
    cout << "YES\n";
    return ;
  }else{
    rep(i , (int)chc.size() - 1){
      // mycout << chc[i] << " " << chc[i+1] << "\n";
      if(GO(chc[i] , chc[i+1], n)){
        cout << "YES\n";
        return ;
      }
    }
  }
  cout << "NO\n";
}

int32_t main(int32_t argc, char *argv[])
{
    double t1 = clock() ;
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int TC = 1, t = 0;
    //cin >> TC ;
    while(t++ < TC)
    {
        //cout << "Case #" << t << ": " ;
        solve();
        //cout << endl ;
    }
    mycerr << "Time : " << 1000 *(clock() - t1)/CLOCKS_PER_SEC << " ms\n" ;
    return 0;
}


def swa(n,x,a,b):
    if x == 0:
        ans = abs(a-b)

    k = abs(b-a)
    m = abs(a-x)
    z = abs(b-x)
    ans = max(k,m,z)
    print(ans)

t = int(input())
for i in range(t):
    n,x,a,b = [int(i) for i in input().split()]
    ans = swa(n,x,a,b)
    ans


t=int(input())
def f(n,x,a,b):
    if a>b:#a<b
        a,b=b,a
    while x>0:
        if a==1 and b==n:
            break
        elif a>1:
            a=a-1
            x=x-1
        elif b<n:
            b=b+1
            x=x-1
    return(b-a)
for i in range(0,t):
    n,x,a,b=map(int,input().split())
    print(f(n,x,a,b))


t=int(input())
def f(n,x,a,b):
    if a>b:#a<b
        a,b=b,a
    while x>0:
        if a==1 and b==n:
            break
        elif a>1:
            a=a-1
            x=x-1
        elif b<n:
            b=b+1
    return(b-a)
for i in range(0,t):
    n,x,a,b=map(int,input().split())
    print(f(n,x,a,b))


t=int(input())
def f(n,x,a,b):
    if a>b:#a<b
        a,b=b,a
    while x!=0:
        if a==1 and b==n:
            break
        elif a>1:
            a=a-1
            x=x-1
        elif b<n:
            b=b+1
    return(b-a)
for i in range(0,t):
    n,x,a,b=map(int,input().split())
    print(f(n,x,a,b))


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    c =(2*b[1]+abs(b[2]-b[3])-1)
    if c <= b[0]-1:
        print(c)
    else:
        print(b[0]-1)


a = int(input())
for x in range(a):
	b = list(map(int,input().split()))
	print((b[1]*abs(b[2]-b[3])))


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    c = b[1]+abs(b[2]-b[3])
    if c <= 99:
        print(c)
    else:
        print(99)


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    print((b[1]*abs(b[2]-b[3])))


a = int(input())
for x in range(a):
	b = list(map(int,input().split()))
	print(abs(b[1]*(b[2]-b[3]))


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    c =(2*b[1]+abs(b[2]-b[3]))
    if c <= b[0]-2:
        print(c)
    else:
        print(b[0]-2)


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    c = b[1]+abs(b[2]-b[3])
    if c <= b[0]-1 or :
        print(c)
    else:
        print(b[0]-1)


a = int(input())
for x in range(a):
	b = list(map(int,input().split()))
	print(abs(b[1]*(b[2]-b[3])))


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    c =  (2*b[1]+abs(b[2]-b[3]))
    if c <= b[0]-2:
        print(c)


a = int(input())
for x in range(a):
    b = list(map(int,input().split()))
    c = b[1]+abs(b[2]-b[3])
    if c <= b[0]-1:
        print(c)
    else:
        print(b[0]-1)


# cook your dish here
t = int(input())
while t>0:
    n,x,a,b = map(int, input().split())
    #li = list(map(int, input().split()))
    if abs(a-b) + x >n-1:
        print((n-1))
    else:
        print(abs(a-b)+ x)
    t = t-1


# cook your dish here
t = int(input())
while t>0:
    n,x,a,b = map(int, input().split())
    #li = list(map(int, input().split()))
    if abs(a-b) + x >=n-1:
        print(abs(a-b))
    else:
        print(abs(a-b)+ x)
    t = t-1


# cook your dish here
t = int(input())
while t>0:
    n,x,a,b = map(int, input().split())
    #li = list(map(int, input().split()))
    if abs(a-b) + x >n-1:
        print(abs(a-b))
    else:
        print(abs(a-b)+ x)
    t = t-1


# cook your dish here
t = int(input())
while t>0:
    n,x,a,b = map(int, input().split())
    #li = list(map(int, input().split()))
    if abs(a-b) + x >=n:
        print(abs(a-b))
    else:
        print(abs(a-b)+ x)
    t = t-1


t=int(input())
for i in range(t):
    L = list(map(int,input().split()))
    n=L[0]
    x=L[1]
    a=L[2]
    b=L[3]
    if (abs(b-a)+x>=n):
        print(n-1)
    else:
        print(abs(b-a)+x)


t=int(input())
for i in range(t):
    L = list(map(int,input()))
    n=l[0]
    x=L[1]
    a=L[2]
    b=L[3]
    if (abs(b-a)+x>n):
        print(n-1)
    else:
        print(abs(b-a)+x)


t=int(input())
for i in range(t):
    L = list(map(int,input().split()))
    n=L[0]
    x=L[1]
    a=L[2]
    b=L[3]
    if (abs(b-a)+x>n):
        print(n-1)
    else:
        print(abs(b-a)+x)


t=int(input())
for i in range(t):
  n=int(input())
  x=int(input())
  a=int(input())
  b=int(input())
  if (abs(b-a)+x>n):
    print(n-1)
  else:
    print(abs(b-a)+x)


t=int(input())
for i in range(t):
    L = list(map(int,input()))
    n=L[0]
    x=L[1]
    a=L[2]
    b=L[3]
    if (abs(b-a)+x>n):
        print(n-1)
    else:
        print(abs(b-a)+x)


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 1:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	if n == 2:
		print(1)
	print(abs(a-b+x))


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 1:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	print(abs(a-b+x))


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if n == 2:
		print(1)
		continue
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 2:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	if x >=n - abs(a-b):
		x = n - abs(a-b) - 1
	print(abs(a-b)+x)


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n:
		print(n)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	if a == 0 or b ==0:
		if a == n or b == n:
			print(n)
			continue
	print(abs(a-b+x))


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if n == 2:
		print(1)
		continue
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 1:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	print(abs(a-b)+x)


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	print(abs(a-b+x))


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if n == 2:
		print(1)
		continue
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 2:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	print(abs(a-b)+x)


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if n == 2:
		print(1)
		continue
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 1:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	print(abs(a-b+x))


for _ in range(int(input())):
	n , x , a , b = map(int, input().split())
	if n == 2:
		print(1)
		continue
	if x == 0:
		print(abs(a-b))
		continue
	if x >= n - 2:
		print(n-1)
		continue
	if abs(a-b) == n-1:
		print(abs(a-b))
		continue
	if x > n - abs(a-b):
		x = n - abs(a-b) - 1
	print(abs(a-b)+x)


for _ in range(int(input())):
    n,x,a,b=map(int,input().split())
    if x==0 or max(a,b)==n and min(a,b)==1:
        print(abs(a-b))
    else:
        print(abs(a+x-b))


for _ in range(int(input())):
    n,x,a,b=map(int,input().split())
    if x==0 or (max(a,b)==n and min(a,b)==1):
        print(abs(a-b))
    else:
        print(abs(a+x-b))


for _ in range(int(input())):
    inp=list(map(int,input().split()))
    n,x,a,b=inp[0],inp[1],inp[2],inp[3]
    if x==0 or abs(a-b)==abs(n-1):
        print(abs(a-b))
    else:
        print(abs(a+x-b))


for _ in range(int(input())):
    n,x,a,b=map(int,input().split())
    if abs(a-b)+x>=n:
        print(n-1)
    else:
        print(abs(a-b)+x)


for _ in range(int(input())):
    n,x,a,b=map(int,input().split())
    if x==0 or (max(a,b)==n and min(a,b)==1):
        print(abs(a-b))
    else:
        print(abs(max(a,b)+x-min(a,b)))


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n=int(n)
    x=int(x)
    a=int(a)
    b=int(b)
    for j in range(x):
        if(abs(a-b)==n-1):
            a=a
            b=b
        elif (a>b):
            if((n-b)>(n-a)):
                p=a+1
                a=p

        else:
            if((n-a)>(n-b)):
                p=b+1
                b=p
    print(abs(a-b))


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n=int(n)
    x=int(x)
    a=int(a)
    b=int(b)
    for j in range(x):
        if(abs(a-b)==n-1):
            a=a
            b=b
        elif (a>b):
            if((n-b)>(n-a) and (b-a)!=(n-1)):
                p=b-1
                b=p
            else:
                p=a-1
                a=p
        else:
            if((n-a)>(n-b) and (b-a)!=(n-1)):
                p=b-1
                b=p
            else:
                p=a-1
                a=p
    print(abs(a-b))


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n=int(n)
    x=int(x)
    a=int(a)
    b=int(b)
    for j in range(x):
        if(abs(a-b)==n-1):
            a=a
            b=b
        elif (a>b):
            if((n-b)>(n-a) and (b-a)!=(n-1)):
                p=b-1
                b=p
            else:
                p=a-1
                a=p
        else:
            if((n-a)>(n-b) and (b-a)!=(n-1)):
                p=b-1
                a=p
            else:
                p=a-1
                a=p
    print(abs(a-b))


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n=int(n)
    x=int(x)
    a=int(a)
    b=int(b)
    for j in range(x):
        if(abs(a-b)==n-1):
            a=a
            b=b
        elif (a>b):
            if((n-b)>(n-a) and (b-a)!=(n-1)):
                p=b-1
                b=p
            else:
                p=a-1
                b=p
        else:
            if((n-a)>(n-b) and (b-a)!=(n-1)):
                p=b-1
                b=p
            else:
                p=a-1
                b=p
    print(abs(a-b))


#code
t = int(input())
for _ in range(t):
    n,x,a,b = map(int, input().split())
    ori = abs(a-b)
    if(x==0):
        print(abs(a-b))
    elif(ori==(n-1)):
        print(ori)
    else:
        ori = ori+x
        if(ori>=(n-1)):
            print(n-1)
        else:
            print(ori)


#code
t = int(input())
for _ in range(t):
    n,x,a,b = map(int, input().split())
    ori = abs(a-b)
    if(x==0):
        print(abs(a-b))
    elif(ori==(n-1)):
        print(ori)
    else:
        for i in range(x):
            ori+=x
        if(ori>=(n-1)):
            print(n-1)
        else:
            print(ori)


#code
t = int(input())
for _ in range(t):
    n,x,a,b = map(int, input().split())
    ori = abs(a-b)
    if(x==0):
        print(abs(a-b))
    elif(ori==(n-1)):
        print(ori)
    else:
        f=0
        if(ori<(n-1)):
            for i in range(x):
                ori+=x
            if(ori>=(n-1)):
                f=1
                break
        if(f):
            print(n-1)
        else:
            print(ori)


for i in range(int(input())):
    x=input().split()
    if x[0]==x[2]and(int(x[0])+int(x[1])-int(x[3])>int(x[0])):
        print(int(x[0])-1)
    else:
        print(abs(int(x[3])-int(x[2]))+int(x[1])


for i in range(int(input())):
    x=input().split()
    if ((x[0]==x[2])):
        print(abs(int(x[2])-1))
    else:
        print(abs(int(x[3])-int(x[2]))+int(x[1]))


for i in range(int(input())):
    x=input().split()
    if x[0]==x[2]and(int(x[0])+int(x[1])-int(x[3])>int(x[0])):
        print(int(x[0])-1)
    else:
        print(abs(int(x[3])-int(x[2]))+int(x[1]))


for i in range(int(input())):
    x=input().split()
    if ((x[0]==x[2])) and (x[3]=="1"):
        print(abs(int(x[2])-1))
    else:
        print(abs(int(x[3])-int(x[2]))+int(x[1]))


for i in range(int(input())):
    c = list(map(int,input().split()))
    c1 = c[1]+abs(c[2]-c[3])
    c2 = min(c1,c[0]-1)
    print(c2)


t = int(input())
while t>0:
    t-=1
    n,x,a,b = map(int,input().split(" "))
    k = min(a,b)
    r = max(a,b)
    a=k
    b=r
    s =0
    if a!=1:
        p=max(1,a-x)
        x=x-(a-p)
        p=a
    b=min(100,b+x)
    b = min(n,b)
    s = b-a

    print(s)


t = int(input())
while t>0:
    t-=1
    n,x,a,b = map(int,input().split(" "))
    k = min(a,b)
    r = max(a,b)
    a=k
    b=r
    s =0
    if a!=1:
        a=1
        x-=a
    b=min(100,b+x)
    b = min(n,b)
    s = b-a

    print(s)


t = int(input())
while t>0:
    t-=1
    n,x,a,b = map(int,input().split(" "))
    k = min(a,b)
    r = max(a,b)
    a=k
    b=r
    s =0
    if x>a:
        if a>1:
            a=1
            x-=a
        b=min(100,b+x)
        s = b-a
    else:
        a-=x
        s=b-a
    print(s)


t = int(input())
while t>0:
    t-=1
    n,x,a,b = map(int,input().split(" "))
    k = min(a,b)
    r = max(a,b)
    a=k
    b=r
    s =0
    p = max(1,a-x)
    x = x-(a-p)
    a=p
    b = min(n,b+x)
    s=b-a
    print(s)


t = int(input())
while t>0:
    t-=1
    n,x,a,b = map(int,input().split(" "))
    k = min(a,b)
    r = max(a,b)
    a=k
    b=r
    s =0
    if a!=1:
        a=1
        x-=a
    b=min(100,b+x)
    s = b-a

    print(s)


x = int(input())
y = []
for c in range(x):
    y.append(list(map(int, input().split())))

for c in y:
    t = 0
    t = t + (c[2] - c[3])
    if t < 0:
        t = t*-1
    t = t + c[1]
    if t >= c[0] :
        t = 0
        t = t+c[0]-1

    print(t)


x = int(input())
y = []
for c in range(x):
    y.append(list(map(int, input().split())))

for c in y:
    t = 0
    t = t + (c[2] - c[3])
    if t < 0:
        t = t*-1
    t = t + c[1]
    if t > c[0] :
        t = 0
        t = t+c[0]-1
    else:
        t = t + c[1]
    print(t)


x = int(input())
y = []
for c in range(x):
    y.append(list(map(int, input().split())))

for c in y:
    t = 0
    t = t + (c[2] - c[3])
    if t < 0:
        t = t*-1
    t = t + c[1]
    if t > c[0] :
        t = 0
        t = t+c[0]-1

    print(t)


x = int(input())
y = []
for c in range(x):
    y.append(list(map(int, input().split())))

for c in y:
    t = 0
    t = t + (c[2] - c[3]) + c[1]
    if t > c[0]:
        t = 0
        t = t+c[0]-1
    if t < 0:
        t = t*-1
    print(t)


t = int(input())
for i in range(t):
	n, x, a, b = map(int, input().split())
	a, b = min(a,b), max(a, b)
	d = a -1
	if x >= d:
		d = 1
		x -= (a - 1)
	else:
		d = a - x
	dd = n - b
	if x >= dd:
		dd = n
	else:
		dd = b + x
	print(dd - d)


import math
from decimal import Decimal
import heapq
from collections import deque
def na():
	n = int(input())
	b = [int(x) for x in input().split()]
	return n,b

def nab():
	n = int(input())
	b = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	return n,b,c

def dv():
	n, m = map(int, input().split())
	return n,m

def dva():
	n, m = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	return n,m,b

def eratosthenes(n):
	sieve = list(range(n + 1))
	for i in sieve:
		if i > 1:
			for j in range(i + i, len(sieve), i):
				sieve[j] = 0
	return sorted(set(sieve))

def lol(lst,k):
	k=k%len(lst)
	ret=[0]*len(lst)
	for i in range(len(lst)):
		if i+k<len(lst) and i+k>=0:
			ret[i]=lst[i+k]
		if i+k>=len(lst):
			ret[i]=lst[i+k-len(lst)]
		if i+k<0:
			ret[i]=lst[i+k+len(lst)]
	return(ret)
def nm():
	n = int(input())
	b = [int(x) for x in input().split()]
	m = int(input())
	c = [int(x) for x in input().split()]
	return n,b,m,c

def dvs():
	n = int(input())
	m = int(input())
	return n, m

def fact(a, b):
	c = []
	ans = 0
	f = int(math.sqrt(a))
	for i in range(1, f + 1):
		if a % i == 0:
			c.append(i)
	l = len(c)
	for i in range(l):
		c.append(a // c[i])
	for i in range(len(c)):
		if c[i] <= b:
			ans += 1
	if a / f == f and b >= f:
		return ans - 1
	return ans

t = int(input())
for i in range(t):
	n, x, a, b = map(int, input().split())
	a, b = min(a,b), max(a, b)
	d = a -1
	if x >= d:
		d = 1
		x -= (a - 1)
	else:
		d = a - x
		x = 0
	dd = n - b
	if x >= dd:
		dd = n
	else:
		dd = b + x
	print(dd - d)


t = int(input())
for i in range(t):
	n, x, a, b = map(int, input().split())
	a, b = min(a,b), max(a, b)
	d = a -1
	if x >= d:
		d = 1
		x -= (a - 1)
	else:
		d = a - x
		x = 0
	dd = n - b
	if x >= dd:
		dd = n
	else:
		dd = b + x
	print(dd - d


t = int(input())
for i in range(t) :
    n, x, a, b = map(int, input().split())
    print(min(n-1, abs(a-b)+x))


t = int(input())
for i in range(t) :
    n, x, a, b = map(int, input().split())
    if abs(a-b) == n-1 :
        print(n-1)
    elif x == 0 :
        print(abs(a-b))
    else :
        for i in range(1,x+1) :
            k = abs(a-b) + i
            if k == n-1 :
                print(k)
                break
            print(k)


t = int(input())
for i in range(t) :
    n, x, a, b = map(int, input().split())
    if abs(a-b) == n-1 :
        print(n-1)
    elif x == 0 :
        print(abs(a-b))
    else :
        c = 0
        while c<= x :
            k = abs(a-b) + c
            if k == n-1 :
                print(k)
                break
            c = c+1
        print(k)


for _ in range (int(input())):
    n, x, a, b = map(int,input().split())
    aa = max(a, b)
    bb = min(a, b)
    an = aa - bb
    while (x > 0) and ((n-aa>0 ) or (bb - 1 > 0)):
        an = an + 1
        x = x - 1
        if(n-aa>0 ):
           aa = aa + 1
        else :
            bb = bb - 1
    print(an)


for _ in range (int(input())):
    n, x, a, b = map(int,input().split())
    a = max(a, b)
    b = min(a, b)
    an = a - b
    while (x > 0) and ((n-a>0 ) or (b - 1 > 0)):
        an = an + 1
        x = x - 1
        if(n-a>0 ):
           a = a + 1
        else :
            b = b - 1
    print(an)


t=int(input())
for v in range(t):
    q=[int(w) for w in input().split()]
    n=q[0]
    x=q[1]
    c=q[2]
    d=q[3]
    b=max(a,b)
    a=min(a,b)
    print(min(n-1),b-a+x)


t=int(input())
for v in range(t):
    q=[int(w) for w in input().split()]
    print(min(n-1,(abs(q[2]-q[3])+q[1]))))


t=int(input())
for v in range(t):
    q=[int(w) for w in input().split()]
    print(min(n-1,(abs(q[2]-q[3])+q[1])))


t=int(input())
for v in range(t):
    q=[int(w) for w in input().split()]
    print(min(q[0]-1,(abs(q[2]-q[3])+q[1])))


t=int(input())
for v in range(t):
    q=[int(w) for w in input().split()]
    print(min(q[0]-1,(abs(q[2]-q[3])+q[1]))))


t = int(input())

for _ in range(t):
    n,x,a,b = map(int,input().split())

    if a-b <= n-1:
        print(min(n-1,abs(a-b)+x))
    else:
        print(n-1)


t = int(input())
n,x,a,b = map(int,input().split())

for _ in range(t):
    while x>0 and (a!=n and b!=1):
        if a != n:
            a +=1
        elif b != 1:
            b -= 1
        x -= 1
    print(abs(a-b))


n,x,a,b = map(int,input().split())

while x>0 and (a!=n and b!=1):
    if a != n:
        a +=1
    elif b != 1:
        b -= 1

    x -= 1
print(abs(a-b))


t = int(input())

for _ in range(t):
    n,x,a,b = map(int,input().split())

    if a-b <= n-1:
        print(min(n,abs(a-b)+x))
    else:
        print(n)


t = int(input())

for _ in range(t):
    n,x,a,b = map(int,input().split())
    while x>0 and (a!=n and b!=1):
        if a != n:
            a +=1
        elif b != 1:
            b -= 1
        x -= 1

    print(abs(a-b))


for i in range(int(input())):
    n,x,a,b=list(map(int,input().split()))
    t=[a,b]
    t.sort()
    if t[1]+x<=n:
        print(t[1]+x-t[0])
    elif t[1]+x>n and (t[0]-(x-(n-t[1])))>=1:
        y=(a-(x-(n-b)))
        print((x+t[1])-y)
    elif t[1]+x>n and (t[0]-(x-(n-t[1])))<1:
        print(n-1)
    else:
        print(n-1)


test_cases=int(input())
input_=[]
for i in range(test_cases):
    input_.append(input())

for i in range(len(input_)):
    inputs=input_[i].split()
    n=int(inputs[0])
    x=int(inputs[1])
    a=int(inputs[2])
    b=int(inputs[3])

    curr_dist=abs(a-b)

    max_dist=n-1
    if x==0:
        print(curr_dist)
        continue
    if curr_dist==max_dist:
        print(curr_dist)
        continue
    xx=0
    if a>b:
        while((curr_dist<max_dist)and (xx<x)):
            if a!=n:
                a+=1
                curr_dist+=1
                xx+=1
            elif b!=1:
                b-=1
                curr_dist+=1
                xx+=1
    else:
        while((curr_dist<max_dist)and(xx<x)):
            if b!=n:
                b+=1
                curr_dist+=1
                xx+=1
            elif a!=1:
                a-=1
                curr_dist+=1
                xx+=1

    print(curr_dist)


test_cases=int(input())
input_=[]
for i in range(test_cases):
    input_.append(input())

for i in range(len(input_)):
    inputs=input_[i].split()
    n=int(inputs[0])
    x=int(inputs[1])
    a=int(inputs[2])
    b=int(inputs[3])

    curr_dist=abs(a-b)

    max_dist=n-1
    if x==0:
        print(curr_dist)
        continue
    xx=0
    if a>b:
        while((curr_dist<max_dist)and (xx<=x)):
            if a!=n:
                a+=1
                curr_dist+=1
                xx+=1
            elif b!=1:
                b-=1
                curr_dist+=1
                xx+=1
    else:
        while((curr_dist<max_dist)and(xx<=x)):
            if b!=n:
                b+=1
                curr_dist+=1
                xx+=1
            elif a!=1:
                a-=1
                curr_dist+=1
                xx+=1

    print(curr_dist)


# int(input())
# [int(s) for s in input().split()]
# input()

def solve():
    t = int(input())
    for i in range(t):
        n, x, a, b = [int(s) for s in input().split()]

        a, b = sorted([a,b])

        while b < n and x > 0:
            b += 1
            x -= 1

        while b > 1 and x > 0:
            a -= 1
            x -= 1

        print(abs(a-b))

if __name__ == "__main__":
    solve()


# int(input())
# [int(s) for s in input().split()]
# input()

def solve():
    t = int(input())
    for i in range(t):
        n, x, a, b = [int(s) for s in input().split()]

        a, b = sorted([a, b])

        while b < n and x > 0:
            b += 1
            x -= 1

        while a > 1 and x > 0:
            a -= 1
            x -= 1

        print(abs(a-b))

if __name__ == "__main__":
    solve()


# int(input())
# [int(s) for s in input().split()]
# input()

def solve():
    t = int(input())
    for i in range(t):
        n, x, a, b = [int(s) for s in input().split()]
        while a < n and x > 0:
            a += 1
            x -= 1

        while b > 1 and x > 0:
            b -= 1
            x -= 1

        print(abs(a-b))

if __name__ == "__main__":
    solve()


# int(input())
# [int(s) for s in input().split()]
# input()

def solve():
    t = int(input())
    for i in range(t):
        n, x, a, b = [int(s) for s in input().split()]
        while b < n and x > 0:
            b += 1
            x -= 1

        while a > 1 and x > 0:
            a -= 1
            x -= 1

        print(b-a)

if __name__ == "__main__":
    solve()


t=int(input())
while(t):
    n,x,a,b=map(int,input().split())
    if(x==0):
        print(abs(a-b))
    elif((a==1 and b==n) or (a==n and b==1)):
        print(abs(a-b))
    else:
        m1=max(a,b)
        m2=min(a,b)
        if((m1+x)<=n):
            print((m1+x)-m1)
        elif((m2-x)>=1):
            print(m1-(m2-x))
        elif((m1+x)>n or (m2-x)<1):
            z=n-m1
            z1=x-z
            print((m1+z)-(m2-z1))
    t=t-1


t=int(input())
while(t):
    n,x,a,b=map(int,input().split())
    if(x==0):
        print(abs(a-b))
    elif((a==1 and b==n) or (a==n and b==1)):
        print(abs(a-b))
    else:
        if(a>b):
            a=a+x
            print(abs(b-a))
        else:
            a=a-x
            print(abs(b-a))
    t=t-1


t=int(input())
while(t):
    n,x,a,b=map(int,input().split())
    if(x==0):
        print(abs(a-b))
    elif((a==1 and b==n) or (a==n and b==1)):
        print(abs(a-b))
    else:
        m1=min(a,b)
        m2=max(a,b)
        z=m1
        z1=n-m2
        if(z<=x and z1<=x):
            print(n-1)
        elif(z>x and z1>x):
            print(m2+x-m1)
        elif(z>=x and z1<=x):
            print(m2-(m1-x))
        elif(z<=x and z1>=x):
            print((m2+x)-m1)
    t=t-1


t=int(input())
while(t):
    n,x,a,b=map(int,input().split())
    if(x==0):
        print(abs(a-b))
    elif((a==1 and b==n) or (a==n and b==1)):
        print(abs(a-b))
    else:
        m1=max(a,b)
        m2=min(a,b)
        if((m1+x)<=n):
            print((m1+x)-m2)
        elif((m2-x)>=1):
            print(m1-(m2-x))
        elif((m1+x)>n or (m2-x)<1):
            z=n-m1
            z1=x-z
            if(z1>=m2):
                print((m1 + z) - 1)
            else:
                print((m1+z)-(m2-z1))
    t=t-1


t=int(input())
while(t):
    n,x,a,b=map(int,input().split())
    if(x==0):
        print(abs(a-b))
    elif((a==1 and b==n) or (a==n and b==1)):
        print(abs(a-b))
    else:
        m1=max(a,b)
        m2=min(a,b)
        if((m1+x)<=n):
            print((m1+x)-m2)
        elif((m2-x)>=1):
            print(m1-(m2-x))
        elif((m1+x)>n or (m2-x)<1):
            z=n-m1
            z1=x-z
            print((m1+z)-(m2-z1))
    t=t-1


n = int(input())
count = 0

dist = []

while count < n :
    q = input()
    q = [int(x) for x in q.split()]
    t = q[0]
    x = q[1]
    a = q[2]
    b = q[3]
    if abs(a-b) == t-1:
        dist.append(t-1)
    else:
        if (x!= 0 ):
            q.pop(0)
            q.pop(0)
            q = sorted(q)
            flag = 0
            if (q[0] - 1) < x:
                flag = 1
                x = x - (q[0]-1)
                new_a = 1
            else:
                new_a = q[0] - x
                x = 0
                dist.append(abs(new_a-b))
            if flag == 1:
                new_b = q[1] + x
                if new_b > t :
                    new_b = t
                dist.append(abs(new_a-new_b))
        else:
            dist.append(abs(a-b))
    count +=1

for y in dist:
    print (y)


n = int(input())
count = 0

dist = []

while count < n :
    q = input()
    q = [int(x) for x in q.split()]
    t = q[0]
    x = q[1]
    a = q[2]
    b = q[3]
    if abs(a-b) == t-1:
        dist.append(t-1)
    else:
        if (x!= 0 ):
            q.pop(0)
            q.pop(0)
            q = sorted(q)
            flag = 0
            if (q[0] - 1) < x:
                flag = 1
                x = x - (q[0]-1)
                new_a = 1
            else:
                new_a = q[0] - x
                x = 0
                dist.append(abs(new_a-q[1]))
            if flag == 1:
                new_b = q[1] + x
                if new_b > t :
                    new_b = t
                dist.append(abs(new_a-new_b))
        else:
            dist.append(abs(a-b))
    count +=1

for y in dist:
    print (y)


n = int(input())
count = 0

dist = []

while count < n :
    q = input()
    q = [int(x) for x in q.split()]
    t = q[0]
    x = q[1]
    a = q[2]
    b = q[3]
    if abs(a-b) == t-1:
        dist.append(t-1)
    else:
        if (x!= 0 ):
            q.pop(0)
            q.pop(1)
            q = sorted(q)
            flag = 0
            if (q[0] - 1) < x:
                flag = 1
                x = x - (q[0]-1)
                new_a = 1
            else:
                new_a = q[0] - x
                x = 0
                dist.append(abs(new_a-b))
            if flag == 1:
                new_b = q[1]+ x
                if new_b > t :
                    new_b = t
                dist.append(abs(new_a-new_b))
        else:
            dist.append(abs(a-b))
    count +=1

for y in dist:
    print (y)


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n,x,a,b=int(n),int(x),int(a),int(b)
    if n>=x+(a-b):
        print(x+abs(a-b))
    else:
        print(n-1)


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n,x,a,b=int(n),int(x),int(a),int(b)
    if n>=x+abs(a-b):
        print(x+abs(a-b))
    else:
        print(n-1)


t=int(input())
for i in range(t):
    n,x,a,b=input().split()
    n,x,a,b=int(n),int(x),int(a),int(b)
    if n>x+abs(a-b):
        print(x+abs(a-b))
    else:
        print(n-1)


#Afrikavi
import math
for _ in range(int(input())):
	n,x,a,b=map(int,input().split())
	mini,maxi = min(a,b), max(a,b)
	while x > 0 and mini > 1:
		mini -= 1
		x -= 1
	while x > 0 and maxi < n:
		maxi += 1
		x -= 1
	print(maxi-mini)


#include <bits/stdc++.h>

#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(nullptr)
#define setIO(i, o) freopen(i, "r", stdin), freopen(o, "w", stdout)
#define pb(x) push_back(x)
#define eb(x...) emplace_back(x)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int) (x).size()
#define lc(i) 2*i
#define rc(i) 2*i+1
#define int long long
using namespace std;
using ii = pair<int, int>;
using vii = vector<ii>;
using vi = vector<int>;
using vvi = vector<vi>;
using vb = vector<bool>;
using vvb = vector<vb>;

struct SparseTable {
    int n, k;
    vector<int> a, lg;
    vector<vector<int>> st;

    void init(int x, vector<int> y) {
        n = x;
        lg.resize(n + 1);
        lg[1] = 0;
        for (int i = 2; i <= n; i++) lg[i] = lg[i / 2] + 1;
        k = lg[n];
        a = y;
        st.assign(n + 1, vector<int>(k + 1));
        build();
    }

    int merge(int x, int y) { return a[x] >= a[y] ? x : y; }

    void build() {
        for (int i = 0; i < n; i++) st[i][0] = i;
        for (int j = 1; j <= k; j++)
            for (int i = 0; i + (1 << j) - 1 <= n; i++)
                st[i][j] = merge(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
    }

    int query(int l, int r) {
        int j = lg[r - l + 1];
        return merge(st[l][j], st[r - (1 << j) + 1][j]);
    }
};

signed main() {
    FAST_IO;
#ifdef arujbansal_local
    setIO("input.txt", "output.txt");
#endif

    int n;
    cin >> n;
    vi a(n);
    a[n - 1] = 0;
    for (int i = 0; i < n - 1; i++) {
        cin >> a[i];
        a[i]--;
    }
    SparseTable sparse;
    sparse.init(n, a);
    vi dp(n, 0);
    int ans = 0;
    for (int i = n - 2; i >= 0; i--) {
        int idx = sparse.query(i + 1, a[i]);
        dp[i] = (a[i] - i) + dp[idx] + ((n - 1) - idx) - (2 * (a[i] - idx));
        ans += dp[i];
    }
    cout << ans;
}


#include <bits/stdc++.h>

#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(nullptr)
#define setIO(i, o) freopen(i, "r", stdin), freopen(o, "w", stdout)
#define pb(x) push_back(x)
#define eb(x...) emplace_back(x)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int) (x).size()
#define lc(i) 2*i
#define rc(i) 2*i+1
#define int long long
using namespace std;
using ii = pair<int, int>;
using vii = vector<ii>;
using vi = vector<int>;
using vvi = vector<vi>;
using vb = vector<bool>;
using vvb = vector<vb>;

const int N = 1e5 + 5, MOD = 1e9 + 7, INF = 1e9 + 5;

signed main() {
    FAST_IO;
#ifdef arujbansal_local
    setIO("input.txt", "output.txt");
#endif

    int n;
    cin >> n;
    int a[n];
    for (int i = 1; i < n; i++) cin >> a[i];
    a[n] = 0;
    int ans = 0;
    vi dp(n + 1, 0);
    for (int i = n - 1; i >= 1; i--) {
        dp[i] = (a[i] - i) + dp[a[i]] + (n - a[i]);
        ans += dp[i];
    }
//    for (const auto &x : dp) cout << x << " ";
    cout << ans;
}


#include <bits/stdc++.h>

#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(nullptr)
#define setIO(i, o) freopen(i, "r", stdin), freopen(o, "w", stdout)
#define pb(x) push_back(x)
#define eb(x...) emplace_back(x)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int) (x).size()
#define lc(i) 2*i
#define rc(i) 2*i+1
#define int long long
using namespace std;
using ii = pair<int, int>;
using vii = vector<ii>;
using vi = vector<int>;
using vvi = vector<vi>;
using vb = vector<bool>;
using vvb = vector<vb>;

const int N = 1e5 + 5, MOD = 1e9 + 7, INF = 1e9 + 5;

struct SparseTable {
    int n, k;
    vector<int> a, lg;
    vector<vector<int>> st;

    void init(int x, vector<int> y) {
        n = x;
        lg.resize(n + 1);
        lg[1] = 0;
        for (int i = 2; i <= n; i++) lg[i] = lg[i / 2] + 1;
        k = lg[n];
        a = y;
        st.assign(n + 1, vector<int>(k + 1));
        build();
    }

    int merge(int x, int y) { return a[x] >= a[y] ? x : y; }

    void build() {
        for (int i = 0; i < n; i++) st[i][0] = i;
        for (int j = 1; j <= k; j++)
            for (int i = 0; i + (1 << j) - 1 <= n; i++)
                st[i][j] = merge(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
    }

    int query(int l, int r) {
        int j = lg[r - l + 1];
        return merge(st[l][j], st[r - (1 << j) + 1][j]);
    }
};

signed main() {
    FAST_IO;
#ifdef arujbansal_local
    setIO("input.txt", "output.txt");
#endif

    int n;
    cin >> n;
    vi a(n);
    a[n - 1] = 0;
    for (int i = 0; i < n - 1; i++) {
        cin >> a[i];
        a[i]--;
    }
    SparseTable sparse;
    sparse.init(n, a);
    vi dp(n, 0);
    int ans = 0;
    for (int i = n - 2; i >= 0; i--) {
        int idx = sparse.query(i + 1, a[i]);
        dp[i] = (a[i] - i) + dp[idx] + ((n - 1) - idx) - (2 * (a[i] - idx));
        ans += dp[i];
    }
    cout << ans;
}


#include<bits/stdc++.h>
using namespace std;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

#define ll long long
#define db double
#define el "\n"
#define ld long double
#define rep(i,n) for(int i=0;i<n;i++)
#define rev(i,n) for(int i=n;i>=0;i--)
#define rep_a(i,a,n) for(int i=a;i<n;i++)
#define tr(ds, it) for(auto it=ds.begin(); it!=ds.end(); it++)
#define rtr(ds, it) for(auto it=ds.rbegin(); it!=ds.rend(); it--)
#define all(ds) ds.begin(), ds.end()
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
typedef priority_queue <int> pq;
typedef vector< long long > vi;
typedef pair<long long, long long> ii;
#define o_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define graph vector<vi>

const ll mod = 1000000007;
ll po(ll x, ll n ){
	ll ans=1;
     while(n>0){
     	if(n&1) ans=(ans*x)%mod;
     	x=(x*x)%mod;
     	n/=2;
     }
     return ans;
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	#ifndef ONLINE_JUDGE
	freopen("input.txt", "r" , stdin);
	freopen("output.txt", "w" , stdout);
	#endif
	int T=1;
	//cin >> T;
	while(T--){
		ll n,y;
		cin>>n;
		ll a[n-1];
		rep(i,n-1){
			cin>>y;
			a[i]=--y;
		}
		int z=(int)log2(n-1)+2;
		ii st[n-1][z]={};
		rep(i,n-1) st[i][0]=mp(a[i],i);
		rep_a(i,1,z){
			for(int j=0;j+(1<<i)<n;j++) st[j][i]=max(st[j][i-1],st[j+(1<<(i-1))][i-1]);
		}
		int vis[n-1]={0};
		ll ans=0,mx,lmx,l1,k,cnt;
		ii tmp;
		ll dp[n-1]={};
		vi v,u;
		rep(i,n-1){
			if(!vis[i]){
				//cout<<i<<" "<<":"<<el;
				vis[i]=1;
				mx=a[i];
				l1=i;
				cnt=1;
				ans+=(n-1-l1);
				lmx=a[i];
				while(lmx<n-1){
					k=(int)log2(lmx-l1+1);
					tmp=max(st[i][k],st[lmx-(1<<k)+1][k]);
					mx=tmp.ff;
					l1=tmp.ss;
					if(!vis[l1]){
						vis[l1]=1;
						ans+=(lmx-l1);
						dp[l1]=lmx-l1;
						cnt++;
					}
					else{
						ans-=(cnt*(lmx-l1));
						ans+=(cnt*dp[l1]);
						if(u.size()>0){
							u[u.size()-1]+=(dp[l1]-(lmx-mx));
						}
						//cout<<ans<<el;
						break;
					}
					ans+=(cnt*(n-1-lmx));
					v.pb(l1);
					u.pb(n-1-lmx);
					lmx=mx;
					//cout<<ans<<el;
				}
				if(v.size()>0){
					ll s=0;
					rev(j,v.size()-1){
						s+=u[j];
						dp[v[j]]+=s;
					}
					v.clear();
					u.clear();
				}
			}
		}
		cout<<ans<<el;

	}

	return 0;
}