Problem:
Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24

Solution in C# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Collections;

namespace Atcoder
{
    public class CPair<T, U> : IComparable where T : IComparable<T>
    {
        public readonly T Item1;
        public readonly U Item2;

        public int CompareTo(object obj)
        {
            CPair<T, U> castedObj = (CPair<T, U>)obj;
            return this.Item1.CompareTo(castedObj.Item1);
        }

        public CPair(T t, U u)
        {
            Item1 = t;
            Item2 = u;
        }
    }
    class Pair : IComparable
    {
        public long x;
        public long a;
        public long b;
        public long c;
        public Pair(long X, long Y, long Z, long D)
        {
            x = X; a = Y; b = Z;
            c = D;
        }
        public Pair(long a,long x)
        {
            this.a = a;this.x = x;
        }

        public int CompareTo(object obj)
        {
            Pair kore = (Pair)obj;
            return x.CompareTo(kore.x);
        }
        public static bool operator <=(Pair p1, Pair p2)
        {
            if (p1.x != p2.x) { return p1.x <= p2.x; }
            else { return p1.a <= p2.a; }
        }
        public static bool operator >=(Pair p1, Pair p2)
        {
            if (p1.x != p2.x) { return p1.x >= p2.x; }
            else { return p1.a >= p2.a; }
        }
    }

    class Program
    {
        static bool[] visited;
        static List<int>[] togo;

        static void Main(string[] args)
        {
            long mod = 1000000007;
            StreamScanner scan = new StreamScanner(System.Console.OpenStandardInput());
            long n = scan.Long();
            long[] d = scan.Long(n);
            long[] kosu = new long[n];
            long max = d.Max();
            for (long i = 0; i < n; i++)
            {
                kosu[d[i]]++;
            }
            long ans = 1;
            mod = 998244353;
            Mlong.mod = 998244353;
            for (long i = 0; i <=max; i++)
            {
                if (kosu[i] == 0) { Console.WriteLine(0);return; }
            }
            for (long i = 1; i <= max; i++)
            {
                long togo = (long)Mlong.Pow(kosu[i - 1], kosu[i]);
                ans *= togo;
                ans %= mod;
            }
            Console.WriteLine(ans);

        }



        static bool DFS(int now, int last)
        {
            visited[now] = true;
            for (int i = 0; i < togo[now].Count; i++)
            {
                if (togo[now][i] == last) { continue; }
                if (visited[togo[now][i]]) { return false; }
                if (!DFS(togo[now][i], now)) { return false; }
            }
            return true;
        }



        static int binary_search<T>(T key, T[] moto, Func<int, T, T[], bool> isok)
        {
            int ng = -1;
            int ok = moto.Length;
            while (Math.Abs(ok - ng) > 1)
            {
                int mid = (ok + ng) / 2;
                if (isok(mid, key, moto)) { ok = mid; }
                else { ng = mid; }
            }
            return ok;
        }
        static int binary_search(int key, int[] moto)
        {
            int ng = -1;
            int ok = moto.Length;
            while (Math.Abs(ok - ng) > 1)
            {
                int mid = (ok + ng) / 2;
                if (isOK(mid, key, moto)) { ok = mid; }
                else { ng = mid; }
            }
            return ok;
        }
        static int[] Togo;
        static bool CheckBipartite(int now, int prev, List<int>[] g, int c = 0)//0,-1が想定
        {
            if (Togo == null) Togo = Enumerable.Repeat(-1, g.Length).ToArray();
            foreach (var next in g[now])
            {
                if (next == prev) continue;
                var nextc = Togo[next];
                if (nextc >= 0 && nextc == c) return false;
                if (nextc >= 0) continue;
                Togo[next] = (c + 1) % 2;
                var res = CheckBipartite(next, now, g, (c + 1) % 2);
                if (res == false) return false;
            }
            return true;
        }
        static bool isOK(int index, int key, int[] moto)
        {
            return moto[index] > key;
        }
        public static int bitCount(int k)
        {
            uint i = (uint)k;
            i = i - ((i >> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
            i = (i + (i >> 4)) & 0x0f0f0f0f;
            i = i + (i >> 8);
            i = i + (i >> 16);
            return (int)i & 0x3f;
        }
        static int check(long moto, long tai)
        {
            if (tai % moto != 0) { return 0; }
            while (tai > 1)
            {
                if (tai % moto == 0) { tai /= moto; }
                else if (tai > moto) { tai %= moto; }
                else { tai -= moto; }
            }
            if (tai == 1) { return 1; }
            else { return 0; }
        }

        static bool NextPermutation(int[] array)
        {
            var size = array.Length;
            var ok = false;

            //array[i]<array[i+1]を満たす最大のiを求める
            int i = size - 2;
            for (; 0 <= i; i--)
            {
                if (array[i] < array[i + 1])
                {
                    ok = true;
                    break;
                }
            }

            //全ての要素が降順の場合、NextPermutationは存在しない
            if (ok == false) return false;

            //array[i]<array[j]を満たす最大のjを求める
            int j = size - 1;
            for (; ; j--)
            {
                if (array[i] < array[j]) break;
            }

            //iとjの要素をswapする
            var tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;

            //i以降の要素を反転させる
            Array.Reverse(array, i + 1, size - (i + 1));

            return true;
        }
        static List<int[]> GetAllPermutation(int N)
        {
            var res = new List<int[]>();
            var array = Enumerable.Range(0, N).ToArray();
            do
            {
                var copy = new int[N];
                array.CopyTo(copy, 0);
                res.Add(copy);
            } while (NextPermutation(array));

            return res;
        }
        static List<int[]> GetAllPermutation(int[] array)
        {
            var size = array.Length;
            var res = new List<int[]>();
            do
            {
                var copy = new int[size];
                array.CopyTo(copy, 0);
                res.Add(copy);
            } while (NextPermutation(array));

            return res;
        }

        static long Syakutori(int[] a, long k)//しゃくとり法モデル:連続部分列に含まれるすべての要素の値の和がK以上
        {
            long sum = 0;
            int right = 0;
            long ans = 0;
            for (int left = 0; left < a.Length; left++)
            {
                while (right < a.Length && sum < k)
                {
                    sum += a[right]; right++;

                }
                if (k <= sum) { ans += a.Length - right + 1; }
                if (left == right) { right++; }
                else { sum -= a[left]; }
            }
            return ans;
        }
        static int[] zalgo(String s)
        {
            int n = s.Length;
            int[] ret = new int[n];
            ret[0] = n;
            int i = 1, j = 0;
            while (i < n)
            {
                while (i + j < n && s[j] == s[i + j])
                    ++j;
                ret[i] = j;
                if (j == 0)
                {
                    ++i;
                    continue;
                }
                int k = 1;
                while (i + k < n && k + ret[k] < j)
                {
                    ret[i + k] = ret[k];
                    ++k;
                }
                i += k;
                j -= k;
            }
            return ret;
        }
        static int gcd(int a, int b)
        {
            if (a % b == 0) { return b; }
            return gcd(b, a % b);
        }
        static long gcd(long a, long b)
        {
            if (a % b == 0) { return b; }
            return gcd(b, a % b);
        }
        public static List<long> factorialMemo = new List<long>() { 1 };
        static long Fact(int x)
        {
            for (int i = factorialMemo.Count; i <= x; i++) factorialMemo.Add(factorialMemo.Last() * i);
            return factorialMemo[x];
        }
        static int[] yousogotoplus(int[] a, int[] b)
        {
            int[] c = new int[a.Length];
            for (int i = 0; i < a.Length; i++)
            {
                c[i] = a[i] + b[i];
            }
            return c;
        }
        static int[] yousogotoplus(int[] a, int[,] b, int l)
        {
            int[] c = new int[a.Length];
            for (int i = 0; i < a.Length; i++)
            {
                c[i] = a[i] + b[l, i];
            }
            return c;
        }

        static int[] yousogotoplus(int[,] a, int l)
        {
            int[] c = new int[a.GetLength(1)];
            for (int i = 0; i < a.GetLength(1); i++)
            {
                c[i] = a[l, i];
            }
            return c;
        }

        public static long LowerBound(long[] a, long key)
        {
            long l = 0;
            long r = a.Length;
            long mid;
            while (l < r)
            {
                mid = ((r - l) / 2) + l;
                if (a[mid] <= key)
                    l = mid + 1;
                else
                    r = mid;
            }
            return l;
        }
        public static long LIS(long[] a)
        {
            var dp = Enumerable.Range(0, a.Length).Select(x => long.MaxValue).ToArray();
            for (int i = 0; i < a.Length; i++)
            {
                dp[LowerBound(dp, a[i])] = a[i];
            }
            return LowerBound(dp, long.MaxValue - 1);
        }

        static long DivideWith(long m, long n, List<long> primes)
        {
            while (m % n == 0)
            {
                primes.Add(n);
                m = m / n;
            }
            return m;
        }
        static List<CPair<long, long>> SoinsuBunkai(long num)
        {
            List<CPair<long, long>> primes = new List<CPair<long, long>>();
            List<long> yakusu = new List<long>();
            List<long> yakusu2 = new List<long>();
            for (int i = 2; i * i <= num; i++)
            {

                if (num % i != 0) { continue; }
                yakusu.Add(i);
                if (i * i != num) { yakusu2.Add(num / i); }
            }
            for (int i = 0; i < yakusu.Count; i++)
            {
                if (num % yakusu[i] != 0) { continue; }
                int j = 0;
                for (j = 0; num % yakusu[i] == 0; j++)
                {
                    num /= yakusu[i];
                }
                primes.Add(new CPair<long, long>(yakusu[i], j));
            }
            for (int i = yakusu2.Count - 1; i > 0; i--)
            {
                if (num % yakusu2[i] != 0) { continue; }
                int j = 0;
                for (j = 0; num % yakusu2[i] == 0; j++)
                {
                    num /= yakusu2[i];
                }
                primes.Add(new CPair<long, long>(yakusu2[i], j));
            }
            return primes;
        }
        static IEnumerable<int> Primes(int maxnum)
        {
            // var sieve = new BitArray(maxnum + 1, true);
            bool[] sieve = Enumerable.Repeat(true, maxnum + 1).ToArray();
            int squareroot = (int)Math.Sqrt(maxnum);
            for (int i = 2; i <= squareroot; i++)
            {
                if (sieve[i] == false)
                    continue;
                for (int n = i * 2; n <= maxnum; n += i)
                    sieve[n] = false;
            }
            for (int i = 2; i <= maxnum; i++)
                if (sieve[i] == true)
                    yield return i;
        }
        /*   static long[] SoinsuBunkai(long num)
           {
               if (num == 1)
                   return new long[] { 1 };
               List<long> primes = new List<long>();
               long n = DivideWith(num, 2, primes);
               n = DivideWith(n, 3, primes);
               n = DivideWith(n, 5, primes);
               long i = 0;
               while (n > 1)
               {
                   int[] ps = { 7, 11, 13, 17, 19, 23, 29, 31 };
                   foreach (var p in ps)
                   {
                       // 30m+2, 30m+3, 30m+4, 30m+5, 30m+6、30m+8... は割る必要はない。
                       n = DivideWith(n, i + p, primes);
                       if (n == 1)
                           break;
                   }
                   i += 30;
               }
               return primes.ToArray();
           }*/
        public static int h;
        public static int w;
        public static int BFS(int height, int width, char[,] map)
        {
            int[] dx = new int[] { -1, 0, 0, 1 };
            int[] dy = new int[] { 0, 1, -1, 0 };
            bool[,] visited = new bool[h, w];
            int[,] len = new int[h, w];
            var queue = new Queue<Tuple<int, int>>();
            queue.Enqueue(new Tuple<int, int>(height, width));
            int max = 0;
            visited[height, width] = true;

            while (queue.Count > 0)
            {
                var now = queue.Dequeue();
                for (int i = 0; i < 4; i++)
                {
                    int ny = now.Item1 + dy[i];
                    int nx = now.Item2 + dx[i];
                    if (ny >= h || ny < 0 || nx >= w || nx < 0)
                        continue;
                    if (visited[ny, nx] || map[ny, nx] == '#')
                        continue;
                    visited[ny, nx] = true;
                    len[ny, nx] = len[now.Item1, now.Item2] + 1;
                    max = Math.Max(max, len[ny, nx]);
                    queue.Enqueue(new Tuple<int, int>(ny, nx));
                }
            }
            return max;
        }
        static public List<int> Topological_Sort(List<List<Edge>> G)
        {
            var ret = new List<int>();
            var Nodes = new Queue<int>();
            int N = G.Count();
            var Link = new int[N];
            for (var i = 0; i < N; i++) { Link[i] = 0; }
            for (var i = 0; i < N; i++)
            {
                foreach (var nx in G[i]) { Link[nx.to]++; }
            }
            for (var i = 0; i < N; i++)
            {
                if (Link[i] == 0) { Nodes.Enqueue(i); }
            }

            while (Nodes.Any())
            {
                var nd = Nodes.Dequeue();
                ret.Add(nd);
                foreach (var nx in G[nd])
                {
                    Link[nx.to]--;
                    if (Link[nx.to] == 0)
                    {
                        Nodes.Enqueue(nx.to);
                    }
                }
            }
            return ret;
        }
        static public bool Bit(long x, int dig) => ((1L << dig) & x) != 0;
        static public void Swap<T>(ref T a, ref T b)
        {
            T keep = a;
            a = b;
            b = keep;
        }
        static public void Initialize<T>(ref T[] array, T initialvalue)
        {
            array = Array.ConvertAll(array, x => initialvalue);
        }
        static int[] Manacher(string S)
        {
            int i = 0, j = 0;
            int[] R = new int[S.Length];
            while (i < S.Length)
            {
                while (i - j >= 0 && i + j < S.Length && S[i - j] == S[i + j]) ++j;
                R[i] = j;
                int k = 1;
                while (i - k >= 0 && k + R[i - k] < j) { R[i + k] = R[i - k]; ++k; }
                i += k; j -= k;
            }
            return R;
        }
        /*    static Pair[] a;
    static int SaikiZentansaku(List<int>now,int count,int last,int n,int m)
    {
        List<int> next = new List<int>();
        for (int i = 0; i < now.Count; i++)
        {
            next.Add(now[i]);
        }
        next.Add(last);
        var kore = next.ToArray();
        int ans = 0;
        if(count==n)
        {
            for (int i = 0; i < a.Length; i++)
            {
                int A = a[i].a;
                int b = a[i].b;
                int c = a[i].c;
                int d = a[i].x;
                if (kore[b] - kore[A] == c) { ans += d; }
            }
            return ans;
        }
        for (int i = last; i <= m; i++)
        {
            ans = Math.Max(ans, SaikiZentansaku(next, count + 1, i, n, m));
        }
        return ans;
    }*/
    }
    public class StreamScanner
    {
        public StreamScanner(Stream stream) { str = stream; }
        private readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        private byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        public char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        public char[] Char(int n)
        {
            char[] kore = new char[n];
            for (int i = 0; i < n; i++)
            {
                kore[i] = Char();
            }
            return kore;
        }
        public char[,] Char(int n, int m)
        {
            char[,] kore = new char[n, m];
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    kore[i, j] = Char();
                }
            }
            return kore;
        }
        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        public long[] Long(long n)
        {
            long[] kore = new long[n];
            for (int i = 0; i < n; i++)
            {
                kore[i] = Long();
            }
            return kore;
        }
        public Mlong[] MLong(long n)
        {
            Mlong[] kore = new Mlong[n];
            for (int i = 0; i < n; i++)
            {
                kore[i] = Long();
            }
            return kore;
        }
        public long[,] Long(long h, long w)
        {
            long[,] kore = new long[h, w];
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    kore[i, j] = Long();
                }
            }
            return kore;
        }
        public int Integer() { return (int)Long(); }
        public Mint[] MInteger(long n)
        {
            Mint[] kore = new Mint[n];
            for (int i = 0; i < n; i++)
            {
                kore[i] = Integer();
            }
            return kore;
        }
        public int[] Integer(long n)
        {
            int[] kore = new int[n];
            for (int i = 0; i < n; i++)
            {
                kore[i] = (int)Long();
            }
            return kore;
        }
        public int[,] Integer(long h, long w)
        {
            int[,] kore = new int[h, w];
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    kore[i, j] = (int)Long();
                }

            }
            return kore;
        }

        public int[] StringToInt(int n)
        {
            char[] s = Scan().ToCharArray();
            int[] kore = new int[n];
            for (int i = 0; i < n; i++)
            {
                kore[i] = s[i] - '0';
            }
            return kore;
        }
        public int[,] StringToInt(int h, int w)
        {

            int[,] kore = new int[h, w];
            for (int i = 0; i < h; i++)
            {
                char[] s = Scan().ToCharArray();
                for (int j = 0; j < w; j++)
                {
                    kore[i, j] = s[j] - '0';
                }

            }
            return kore;
        }

        public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    public class UnionFind
    {
        public int[] data;

        public UnionFind(int size)
        {
            data = new int[size];
            for (int i = 0; i < size; i++) data[i] = -1;
        }

        public bool Unite(int x, int y)
        {
            x = Root(x);
            y = Root(y);

            if (x != y)
            {
                if (data[y] < data[x])
                {
                    var tmp = y;
                    y = x;
                    x = tmp;
                }
                data[x] += data[y];
                data[y] = x;
            }
            return x != y;
        }

        public bool IsSameGroup(int x, int y)
        {
            return Root(x) == Root(y);
        }

        public int Root(int x)
        {
            return data[x] < 0 ? x : data[x] = Root(data[x]);
        }
    }
    public class Mlong : IComparable
    {
        public static long mod = 1000000007;
        public long num;
        public Mlong(long num) { this.num = num; }
        public override int GetHashCode()
        {
            return num.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            return num.Equals(obj);
        }
        public static Mlong operator +(Mlong x, Mlong y)
        {
            return new Mlong((x.num + y.num) % mod);
        }
        public static Mlong operator -(Mlong x, Mlong y)
        {
            return new Mlong((x.num - y.num + mod) % mod);
        }
        public static Mlong operator *(Mlong x, Mlong y)
        {
            return new Mlong((long)(((1L * x.num) * y.num) % mod));
        }
        public Mlong hutujyo(Mlong x)
        {
            return new Mlong(num / x.num);
        }
        static long GetInverse(long a)
        {
            long div, p = mod, x1 = 1, y1 = 0, x2 = 0, y2 = 1;
            while (true)
            {
                if (p == 1) return x2 + mod; div = a / p; x1 -= x2 * div; y1 -= y2 * div; a %= p;
                if (a == 1) return x1 + mod; div = p / a; x2 -= x1 * div; y2 -= y1 * div; p %= a;
            }
        }
        public Mlong modjyo(Mlong x)
        {
            return num * GetInverse(x.num) % mod;
        }
        public static implicit operator Mlong(long x)
        {
            return new Mlong(x);
        }
        public static Mlong operator %(Mlong x, Mlong y)
        {
            return new Mlong(x.num % y.num);
        }
        public static explicit operator long(Mlong x)
        {
            return x.num;
        }
        public static bool operator ==(Mlong x, Mlong y)
        {
            return x.num == y.num;
        }
        public static bool operator !=(Mlong x, Mlong y)
        {
            return x.num != y.num;
        }
        public static bool operator <(Mlong x, Mlong y)
        {
            return x.num < y.num;
        }
        public static bool operator >(Mlong x, Mlong y)
        {
            return x.num > y.num;
        }
        public static bool operator <=(Mlong x, Mlong y)
        {
            return x.num <= y.num;
        }
        public static bool operator >=(Mlong x, Mlong y)
        {
            return x.num >= y.num;
        }
        public Mlong Pow(Mlong n)
        {
            Mlong pow = this;
            Mlong res = 1;
            while (n > 0)
            {
                if (n % 2 == 1) { res *= pow; }
                pow *= pow;
                n=n.hutujyo(2);
            }
            /*   if (n == 1) { return this % mod; }
               if (n % 2 == 1) { return (this * Pow(n - 1)) % mod; }
               Mint buf = Pow(n.hutujyo(2));
               return (buf * buf) % mod;*/
            return res;
        }
        public static Mlong Pow(Mlong a, Mlong n)
        {
            return a.Pow(n);
        }
        public static List<Mlong> factorialMemo = new List<Mlong>() { 1 };
        static Mlong Factorial(int x)
        {
            for (int i = factorialMemo.Count; i <= x; i++) factorialMemo.Add(factorialMemo.Last() * i);
            return factorialMemo[x];
        }
        public static Mlong Comb(Mlong n, Mlong a)
        {
            Mlong buf1 = 1;
            Mlong buf2 = 1;
            for (long i = 0; i < a.num; i++)
            {
                buf1 *= n - i;
                buf2 *= (i + 1);
            }
            return buf1.modjyo(buf2);

        }

        public static Mlong Comb(int n, int r)
        {
            return Factorial(n).modjyo(Factorial(r)).modjyo(Factorial(n - r));
        }
        public static void WriteLine(Mlong x)
        {
            Console.WriteLine(x.num);

        }

        public int CompareTo(object obj)
        {
            Mlong kore = (Mlong)obj;
            return num.CompareTo(kore.num);
        }
    }
    public class Mint : IComparable
    {
        public static int mod = 1000000007;
        public int num;
        public Mint(int Num) { num = Num; }
        public override int GetHashCode()
        {
            return num.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            return num.Equals(obj);
        }
        public static Mint operator +(Mint x, Mint y)
        {
            return new Mint((x.num + y.num) % mod);
        }
        public static Mint operator -(Mint x, Mint y)
        {
            return new Mint((x.num - y.num + mod) % mod);
        }
        public static Mint operator *(Mint x, Mint y)
        {
            return new Mint((int)(((1L * x.num) * y.num) % mod));
        }
        public Mint hutujyo(Mint x)
        {
            return new Mint(num / x.num);
        }

        static int GetInverse(long a)
        {
            long div, p = mod, x1 = 1, y1 = 0, x2 = 0, y2 = 1;
            while (true)
            {
                if (p == 1) return (int)(x2 + mod); div = a / p; x1 -= x2 * div; y1 -= y2 * div; a %= p;
                if (a == 1) return (int)(x1 + mod); div = p / a; x2 -= x1 * div; y2 -= y1 * div; p %= a;
            }
        }
        public Mint modjyo(Mint x)
        {
            return num * GetInverse(x.num) % mod;
        }
        /*  public Mint modjyo(Mint x)
          {
              return num * x.Pow(mod - 2);
          }*/
        public static implicit operator Mint(int x)
        {
            return new Mint(x);
        }
        public static Mint[] Toarray(int[] x)
        {
            Mint[] buf = new Mint[x.Length];
            for (int i = 0; i < x.Length; i++)
            {
                buf[i] = x[i];
            }
            return buf;
        }
        public static explicit operator int(Mint x)
        {
            return x.num;
        }
        public static Mint operator %(Mint x, Mint y)
        {
            return new Mint(x.num % y.num);
        }
        public static bool operator ==(Mint x, Mint y)
        {
            return x.num == y.num;
        }
        public static bool operator !=(Mint x, Mint y)
        {
            return x.num != y.num;
        }
        public static bool operator <(Mint x, Mint y)
        {
            return x.num < y.num;
        }
        public static bool operator >(Mint x, Mint y)
        {
            return x.num > y.num;
        }
        public static bool operator <=(Mint x, Mint y)
        {
            return x.num <= y.num;
        }
        public static bool operator >=(Mint x, Mint y)
        {
            return x.num >= y.num;
        }
        public Mint Pow(Mint n)
        {
            Mint pow = this;
            Mint res = 1;
            while (n > 0)
            {
                if (n % 2 == 1) { res *= pow; }
                pow *= pow;
                n.hutujyo(2);
            }
            /*   if (n == 1) { return this % mod; }
               if (n % 2 == 1) { return (this * Pow(n - 1)) % mod; }
               Mint buf = Pow(n.hutujyo(2));
               return (buf * buf) % mod;*/
            return res;
        }
        public static Mint Pow(Mint a, Mint n)
        {
            return a.Pow(n);
        }
        public static List<Mint> factorialMemo = new List<Mint>() { 1 };
        static Mint Factorial(int x)
        {
            for (int i = factorialMemo.Count; i <= x; i++) factorialMemo.Add(factorialMemo.Last() * i);
            return factorialMemo[x];
        }


        public static Mint Comb(int n, int r)
        {
            return Factorial(n).modjyo(Factorial(r)).modjyo(Factorial(n - r));
        }
        public static void WriteLine(Mint x)
        {
            Console.WriteLine(x.num);

        }
        public int CompareTo(object obj)
        {
            Mint kore = (Mint)obj;
            return num.CompareTo(kore.num);
        }
    }
    public class PriorityQueue<T> : IEnumerable<T>
    {
        private readonly List<T> _data = new List<T>();
        private readonly IComparer<T> _comparer;
        private readonly bool _isDescending;

        public PriorityQueue(IComparer<T> comparer, bool isDescending = true)
        {
            _comparer = comparer;
            _isDescending = isDescending;
        }

        public PriorityQueue(Comparison<T> comparison, bool isDescending = true)
            : this(Comparer<T>.Create(comparison), isDescending)
        {
        }

        public PriorityQueue(bool isDescending = true)
            : this(Comparer<T>.Default, isDescending)
        {
        }

        public void Enqueue(T item)
        {
            _data.Add(item);
            var childIndex = _data.Count - 1;
            while (childIndex > 0)
            {
                var parentIndex = (childIndex - 1) / 2;
                if (Compare(_data[childIndex], _data[parentIndex]) >= 0)
                    break;
                Swap(childIndex, parentIndex);
                childIndex = parentIndex;
            }
        }

        public T Dequeue()
        {
            var lastIndex = _data.Count - 1;
            var firstItem = _data[0];
            _data[0] = _data[lastIndex];
            _data.RemoveAt(lastIndex--);
            var parentIndex = 0;
            while (true)
            {
                var childIndex = parentIndex * 2 + 1;
                if (childIndex > lastIndex)
                    break;
                var rightChild = childIndex + 1;
                if (rightChild <= lastIndex && Compare(_data[rightChild], _data[childIndex]) < 0)
                    childIndex = rightChild;
                if (Compare(_data[parentIndex], _data[childIndex]) <= 0)
                    break;
                Swap(parentIndex, childIndex);
                parentIndex = childIndex;
            }
            return firstItem;
        }

        public T Peek()
        {
            return _data[0];
        }

        private void Swap(int a, int b)
        {
            var tmp = _data[a];
            _data[a] = _data[b];
            _data[b] = tmp;
        }

        private int Compare(T a, T b)
        {
            return _isDescending ? _comparer.Compare(b, a) : _comparer.Compare(a, b);
        }

        public int Count => _data.Count;

        public IEnumerator<T> GetEnumerator()
        {
            return _data.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
    public class Tree
    {
        public Node[] Nodes;
        public List<int[]> hen;
        public class Node
        {
            public int? parent = null;
            public List<int[]> children = new List<int[]>();
            public int parentcolor = -1;
        }
        public Tree(int kosu)
        {
            Nodes = new Node[kosu];
            for (int i = 0; i < Nodes.Length; i++)
            {
                Nodes[i] = new Node();
            }
            hen = new List<int[]>();
        }
        public void Connect(int oya, int ko, int id)
        {
            hen.Add(new int[] { oya, ko, 0 });
            Nodes[oya].children.Add(new int[] { ko, id });
            Nodes[ko].parent = oya;
        }
    }
    /// <summary>
    /// Self-Balancing Binary Search Tree
    /// (using Randamized BST)
    /// </summary>
    public class SB_BinarySearchTree<T> where T : IComparable
    {
        public class Node
        {
            public T Value;
            public Node LChild;
            public Node RChild;
            public int Count;     //size of the sub tree

            public Node(T v)
            {
                Value = v;
                Count = 1;
            }
        }

        static Random _rnd = new Random();

        public static int Count(Node t)
        {
            return t == null ? 0 : t.Count;
        }

        static Node Update(Node t)
        {
            t.Count = Count(t.LChild) + Count(t.RChild) + 1;
            return t;
        }

        public static Node Merge(Node l, Node r)
        {
            if (l == null || r == null) return l == null ? r : l;

            if ((double)Count(l) / (double)(Count(l) + Count(r)) > _rnd.NextDouble())
            {
                l.RChild = Merge(l.RChild, r);
                return Update(l);
            }
            else
            {
                r.LChild = Merge(l, r.LChild);
                return Update(r);
            }
        }

        /// <summary>
        /// split as [0, k), [k, n)
        /// </summary>
        public static Tuple<Node, Node> Split(Node t, int k)
        {
            if (t == null) return new Tuple<Node, Node>(null, null);
            if (k <= Count(t.LChild))
            {
                var s = Split(t.LChild, k);
                t.LChild = s.Item2;
                return new Tuple<Node, Node>(s.Item1, Update(t));
            }
            else
            {
                var s = Split(t.RChild, k - Count(t.LChild) - 1);
                t.RChild = s.Item1;
                return new Tuple<Node, Node>(Update(t), s.Item2);
            }
        }

        public static Node Remove(Node t, T v)
        {
            if (Find(t, v) == null) return t;
            return RemoveAt(t, LowerBound(t, v));
        }

        public static Node RemoveAt(Node t, int k)
        {
            var s = Split(t, k);
            var s2 = Split(s.Item2, 1);
            return Merge(s.Item1, s2.Item2);
        }

        public static bool Contains(Node t, T v)
        {
            return Find(t, v) != null;
        }

        public static Node Find(Node t, T v)
        {
            while (t != null)
            {
                var cmp = t.Value.CompareTo(v);
                if (cmp > 0) t = t.LChild;
                else if (cmp < 0) t = t.RChild;
                else break;
            }
            return t;
        }

        public static Node FindByIndex(Node t, int idx)
        {
            if (t == null) return null;

            var currentIdx = Count(t) - Count(t.RChild) - 1;
            while (t != null)
            {
                if (currentIdx == idx) return t;
                if (currentIdx > idx)
                {
                    t = t.LChild;
                    currentIdx -= (Count(t == null ? null : t.RChild) + 1);
                }
                else
                {
                    t = t.RChild;
                    currentIdx += (Count(t == null ? null : t.LChild) + 1);
                }
            }

            return null;
        }

        public static int UpperBound(Node t, T v)
        {
            var torg = t;
            if (t == null) return -1;

            var ret = Int32.MaxValue;
            var idx = Count(t) - Count(t.RChild) - 1;
            while (t != null)
            {
                var cmp = t.Value.CompareTo(v);

                if (cmp > 0)
                {
                    ret = Math.Min(ret, idx);
                    t = t.LChild;
                    idx -= (Count(t == null ? null : t.RChild) + 1);
                }
                else if (cmp <= 0)
                {
                    t = t.RChild;
                    idx += (Count(t == null ? null : t.LChild) + 1);
                }
            }
            return ret == Int32.MaxValue ? Count(torg) : ret;
        }

        public static int LowerBound(Node t, T v)
        {
            var torg = t;
            if (t == null) return -1;

            var idx = Count(t) - Count(t.RChild) - 1;
            var ret = Int32.MaxValue;
            while (t != null)
            {
                var cmp = t.Value.CompareTo(v);
                if (cmp >= 0)
                {
                    if (cmp == 0) ret = Math.Min(ret, idx);
                    t = t.LChild;
                    if (t == null) ret = Math.Min(ret, idx);
                    idx -= t == null ? 0 : (Count(t.RChild) + 1);
                }
                else if (cmp < 0)
                {
                    t = t.RChild;
                    idx += (Count(t == null ? null : t.LChild) + 1);
                    if (t == null) return idx;
                }
            }
            // return ret;
            return ret == Int32.MaxValue ? Count(torg) : ret;
        }

        public static Node Insert(Node t, T v)
        {
            var ub = LowerBound(t, v);
            return InsertByIdx(t, ub, v);
        }

        static Node InsertByIdx(Node t, int k, T v)
        {
            var s = Split(t, k);
            return Merge(Merge(s.Item1, new Node(v)), s.Item2);
        }

        public static IEnumerable<T> Enumerate(Node t)
        {
            var ret = new List<T>();
            Enumerate(t, ret);
            return ret;
        }

        static void Enumerate(Node t, List<T> ret)
        {
            if (t == null) return;
            Enumerate(t.LChild, ret);
            ret.Add(t.Value);
            Enumerate(t.RChild, ret);
        }
    }

    /// <summary>
    /// C-like set
    /// </summary>
    public class Set<T> where T : IComparable
    {
        protected SB_BinarySearchTree<T>.Node _root;

        public T this[int idx] { get { return ElementAt(idx); } }

        public int Count()
        {
            return SB_BinarySearchTree<T>.Count(_root);
        }

        public virtual void Insert(T v)
        {
            if (_root == null) _root = new SB_BinarySearchTree<T>.Node(v);
            else
            {
                if (SB_BinarySearchTree<T>.Find(_root, v) != null) return;
                _root = SB_BinarySearchTree<T>.Insert(_root, v);
            }
        }

        public void Clear()
        {
            _root = null;
        }

        public void Remove(T v)
        {
            _root = SB_BinarySearchTree<T>.Remove(_root, v);
        }

        public bool Contains(T v)
        {
            return SB_BinarySearchTree<T>.Contains(_root, v);
        }

        public T ElementAt(int k)
        {
            var node = SB_BinarySearchTree<T>.FindByIndex(_root, k);
            if (node == null) throw new IndexOutOfRangeException();
            return node.Value;
        }

        public int Count(T v)
        {
            return SB_BinarySearchTree<T>.UpperBound(_root, v) - SB_BinarySearchTree<T>.LowerBound(_root, v);
        }

        public int LowerBound(T v)
        {
            return SB_BinarySearchTree<T>.LowerBound(_root, v);
        }

        public int UpperBound(T v)
        {
            return SB_BinarySearchTree<T>.UpperBound(_root, v);
        }

        public Tuple<int, int> EqualRange(T v)
        {
            if (!Contains(v)) return new Tuple<int, int>(-1, -1);
            return new Tuple<int, int>(SB_BinarySearchTree<T>.LowerBound(_root, v), SB_BinarySearchTree<T>.UpperBound(_root, v) - 1);
        }

        public List<T> ToList()
        {
            return new List<T>(SB_BinarySearchTree<T>.Enumerate(_root));
        }
    }

    /// <summary>
    /// C-like multiset
    /// </summary>
    public class MultiSet<T> : Set<T> where T : IComparable
    {
        public override void Insert(T v)
        {
            if (_root == null) _root = new SB_BinarySearchTree<T>.Node(v);
            else _root = SB_BinarySearchTree<T>.Insert(_root, v);
        }
    }
    public class RollingHashSlow
    {
        public const long B = (long)1e5 + 7;
        public const long MOD = (long)1e9 + 7;
        public string S { get; set; }
        public int N { get; set; }
        public long[] Power { get; set; }
        public long[] Hash { get; set; }
        public RollingHashSlow(string s)
        {
            this.S = s;
            this.N = s.Length;
            // B^nを計算しておく
            this.Power = new long[this.N + 1];
            this.Power[0] = 1;
            for (int i = 0; i < N; i++)
            {
                this.Power[i + 1] = (this.Power[i] * B) % MOD;
            }
            // ハッシュを前計算する
            this.Hash = new long[this.N + 1];
            for (int i = 0; i < N; i++)
            {
                this.Hash[i + 1] = (this.Hash[i] * B + S[i]) % MOD;
            }
        }
        // S[l, r) のハッシュ値を求める
        public long Get(int l, int r)
        {
            var hash = this.Hash[r] - (this.Hash[l] * this.Power[r - l] % MOD);
            if (hash < 0) hash += MOD;
            return hash;
        }
    }
    class RollingHashFast
    {
        public const ulong B = (ulong)1e9 + 7;
        public string S { get; set; }
        public int N { get; set; }
        public ulong[] Power { get; set; }
        public ulong[] Hash { get; set; }
        public RollingHashFast(string s)
        {
            this.S = s;
            this.N = s.Length;
            // B^nを計算しておく
            this.Power = new ulong[this.N + 1];
            this.Power[0] = 1;
            for (int i = 0; i < N; i++)
            {
                this.Power[i + 1] = this.Power[i] * B;
            }
            // ハッシュを前計算する
            this.Hash = new ulong[this.N + 1];
            for (int i = 0; i < N; i++)
            {
                this.Hash[i + 1] = this.Hash[i] * B + S[i];
            }
        }
        // [l, r) のハッシュ値を求める
        public ulong Get(int l, int r)
        {
            var hash = this.Hash[r] - (this.Hash[l] * this.Power[r - l]);
            return hash;
        }
    }
    class Segtree<T>
    {
        int n;
        T[] tree;
        Func<T, T, T> f;
        T exnum;
        public Segtree(int m, Func<T, T, T> f, T ex)
        {
            this.f = f;
            this.exnum = ex;
            n = 1;
            while (n < m) n <<= 1;

            tree = new T[(n << 1) - 1];
            for (int i = 0; i < tree.Length; i++) tree[i] = ex;
        }
        public Segtree(int m, T ini, Func<T, T, T> f, T ex) : this(m, f, ex)
        {
            for (int i = 0; i < m; ++i) tree[i + n - 1] = ini;
            all_update();
        }
        public void assign_without_update(int j, T x)
        {
            tree[j + n - 1] = x;
        }
        public void update(int j, T x)
        {
            int i = j + n - 1;
            tree[i] = x;
            while (i > 0)
            {
                i = (i - 1) >> 1;
                tree[i] = f(tree[(i << 1) + 1], tree[(i << 1) + 2]);
            }
        }
        public void all_update()
        {
            for (int i = n - 2; i >= 0; i--)
                tree[i] = f(tree[(i << 1) + 1], tree[(i << 1) + 2]);
        }
        public T look(int i) { return tree[i + n - 1]; }

        // [s, t)
        public T run(int s, int t) { return query(s, t, 0, 0, n); }
        T query(int s, int t, int k, int l, int r)
        {
            if (r <= s || t <= l) return exnum;
            if (s <= l && r <= t) return tree[k];

            return f(query(s, t, (k << 1) + 1, l, (l + r) >> 1), query(s, t, (k + 1) << 1, (l + r) >> 1, r));
        }

    }
    public class WarshallFloyd
    {
        public int V { get; set; }
        public long[,] DP { get; set; }
        public long INF = long.MaxValue;
        public bool[] Negative;
        public WarshallFloyd(int v)
        {
            this.V = v;
            this.DP = new long[V, V];
            for (int i = 0; i < V; i++)
            {
                for (int j = 0; j < V; j++)
                {
                    this.DP[i, j] = INF;
                }
                this.DP[i, i] = 0;
            }
        }
        public void SetCost(int a, int b, int c = 1)
        {
            this.DP[a, b] = c;
        }
        public long[,] CalcMinCost()
        {
            this.Negative = new bool[V];
            for (int k = 0; k < V; k++)
            {
                for (int i = 0; i < V; i++)
                {
                    for (int j = 0; j < V; j++)
                    {
                        if (DP[i, k] == INF || DP[k, j] == INF) continue;
                        DP[i, j] = Math.Min(DP[i, j], DP[i, k] + DP[k, j]);
                    }
                }
            }
            for (int k = 0; k < V; k++)
            {
                for (int i = 0; i < V; i++)
                {
                    for (int j = 0; j < V; j++)
                    {
                        if (DP[i, k] == INF || DP[k, j] == INF) continue;
                        if (DP[i, j] > DP[i, k] + DP[k, j])
                        {
                            this.Negative[i] = true;
                            this.Negative[j] = true;
                            this.Negative[k] = true;
                        }
                    }
                }
            }
            return DP;
        }
        public long GetMinCost(int a, int b)
        {
            return DP[a, b];
        }
        public bool IsINF(int a, int b)
        {
            return DP[a, b] >= INF;
        }
        public bool IsNegative(params int[] vs)
        {
            if (vs.Length == 0) vs = Enumerable.Range(0, V).ToArray();
            foreach (var v in vs)
            {
                if (Negative[v]) return true;
            }
            return false;
        }
    }
    /// <summary>
    /// Get min cost between two points
    /// </summary>
    public class Dijkstra
    {
        private int maxIndex = -1;
        private const int INF = Int32.MaxValue;

        private int[,] _edgeArray;

        /// <summary>
        /// Dijkstra, get min cost between two points
        /// should not contain negatie cost path
        /// </summary>
        /// <param name="size">max index of vertices</param>
        public Dijkstra(int size)
        {
            maxIndex = size + 1;
            _edgeArray = new int[maxIndex, maxIndex];

            for (int i = 0; i < _edgeArray.GetLength(0); i++)
            {
                for (int j = 0; j < _edgeArray.GetLength(1); j++)
                {
                    _edgeArray[i, j] = INF;
                    if (i == j) _edgeArray[i, j] = 0;
                }
            }
        }

        // Add a path(no direction) with its cost
        public void AddPath(int s, int t, int cost)
        {
            _edgeArray[s, t] = Math.Min(_edgeArray[s, t], cost);
            _edgeArray[t, s] = _edgeArray[s, t];
        }

        //Get the min cost between s and t
        //return Int32.MaxValue if no path
        public int GetMinCost(int s, int t)
        {
            int[] cost = new int[maxIndex];
            for (int i = 0; i < cost.Length; i++) cost[i] = INF;
            cost[s] = 0;

            var priorityQueue = new PriorityQueue<CPair<int, int>>();
            priorityQueue.Enqueue(new CPair<int, int>(0, s));

            while (priorityQueue.Count() > 0)
            {
                var costDestinationPair = priorityQueue.Dequeue();
                if (cost[costDestinationPair.Item2] < costDestinationPair.Item1) continue;

                for (int i = 0; i < maxIndex; i++)
                {
                    int newCostToi = _edgeArray[costDestinationPair.Item2, i] == INF ? INF :
                        costDestinationPair.Item1 + _edgeArray[costDestinationPair.Item2, i];
                    if (newCostToi < cost[i])
                    {
                        cost[i] = newCostToi;
                        priorityQueue.Enqueue(new CPair<int, int>(newCostToi, i));
                    }
                }
            }

            return cost[t];
        }
    }
    class Deque<T> : IEnumerable<T>
    {
        public T this[int i]
        {
            get { return this.Buffer[(this.FirstIndex + i) % this.Capacity]; }
            set
            {
                if (i < 0) throw new ArgumentOutOfRangeException();
                this.Buffer[(this.FirstIndex + i) % this.Capacity] = value;
            }
        }
        private T[] Buffer;
        private int Capacity;
        private int FirstIndex;
        private int LastIndex
        {
            get { return (this.FirstIndex + this.Length) % this.Capacity; }
        }
        public int Length;
        public Deque(int capacity = 16)
        {
            this.Capacity = capacity;
            this.Buffer = new T[this.Capacity];
            this.FirstIndex = 0;
        }
        public void PushBack(T data)
        {
            if (this.Length == this.Capacity) this.Resize();
            this.Buffer[this.LastIndex] = data;
            this.Length++;
        }
        public void PushFront(T data)
        {
            if (this.Length == this.Capacity) this.Resize();
            var index = this.FirstIndex - 1;
            if (index < 0) index = this.Capacity - 1;
            this.Buffer[index] = data;
            this.Length++;
            this.FirstIndex = index;
        }
        public T PopBack()
        {
            if (this.Length == 0) throw new InvalidOperationException("データが空です。");
            var data = this[this.Length - 1];
            this.Length--;
            return data;
        }
        public T PopFront()
        {
            if (this.Length == 0) throw new InvalidOperationException("データが空です。");
            var data = this[0];
            this.FirstIndex++;
            this.FirstIndex %= this.Capacity;
            this.Length--;
            return data;
        }
        private void Resize()
        {
            var newArray = new T[this.Capacity * 2];
            for (int i = 0; i < this.Length; i++)
            {
                newArray[i] = this[i];
            }
            this.FirstIndex = 0;
            this.Capacity *= 2;
            this.Buffer = newArray;
        }
        public IEnumerator<T> GetEnumerator()
        {
            for (int i = 0; i < this.Length; i++)
            {
                yield return this[i];
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            for (int i = 0; i < this.Length; i++)
            {
                yield return this[i];
            }
        }
    }
    public struct Edge
    {
        public int from;

        public int to;
        public long dist;

        public Edge(int t, long c)
        {
            from = -1;
            to = t;
            dist = c;
        }
        public Edge(int f, int t, long c)
        {
            from = f;
            to = t;
            dist = c;
        }
    }
    public class PotentializedUnionFind
    {
        int _count;
        int[] par, sizes, rank;
        long[] weight;
        public PotentializedUnionFind(int N)
        {
            _count = N;
            par = new int[N];
            sizes = new int[N];
            rank = new int[N];
            weight = new long[N];
            for (int i = 0; i < N; ++i)
            {
                par[i] = i;
                sizes[i] = 1;
                rank[i] = 0;
            }
        }
        int Root(int X)
        {
            if (par[X] == X)
            {
                return X;
            }
            else
            {
                int r = Root(par[X]);
                weight[X] += weight[par[X]];
                return (par[X] = r);
            }
        }
        public bool Merge(int X, int Y, long W)
        {
            W += GetWeight(X);
            W -= GetWeight(Y);
            X = Root(X);
            Y = Root(Y);
            if (X == Y) return false;
            --_count;
            if (rank[X] < rank[Y])
            {
                par[X] = Y;
                sizes[Y] += sizes[X];
                weight[X] = -W;
            }
            else
            {
                par[Y] = X;
                sizes[X] += sizes[Y];
                if (rank[X] == rank[Y]) ++rank[X];
                weight[Y] = W;
            }
            return true;
        }
        public bool IsSame(int X, int Y) => Root(X) == Root(Y);
        public int Count => _count;
        public bool IsParent(int X) => X == Root(X);
        public int GetParent(int X) => Root(X);
        public int Size(int X) => sizes[Root(X)];
        public long GetWeight(int X) { Root(X); return weight[X]; }
        public long GetDiff(int X, int Y) => GetWeight(Y) - GetWeight(X);
    }
    public static class BellmanFord
    {
        public class Vertex
        {
            public long Distance { get; set; }

            public Vertex()
            {
                Distance = long.MaxValue;
            }
        }

        public class Edge
        {
            public int From { get; private set; }
            public int To { get; private set; }
            public long Weight { get; private set; }

            public Edge(int from, int to, long weight)
            {
                From = from;
                To = to;
                Weight = weight;
            }
        }

        private static void GetReachable(int origin, ref HashSet<int> reached, ref Dictionary<int, int[]> paths)
        {
            if (reached.Contains(origin))
                return;

            reached.Add(origin);

            if (paths.ContainsKey(origin) == false)
                return;

            foreach (var p in paths[origin])
                GetReachable(p, ref reached, ref paths);
        }

        /// <summary>
        /// null: 負の無限大
        /// long.MaxValue: たどり着けない
        /// その他: 距離
        /// </summary>
        public static long? RunBellmanFord(int vertexCount, List<Edge> rawEdges, int source, int dest)
        {
            var forwards = rawEdges.GroupBy(x => x.From).ToDictionary(x => x.Key, x => x.Select(xs => xs.To).ToArray());
            var reverses = rawEdges.GroupBy(x => x.To).ToDictionary(x => x.Key, x => x.Select(xs => xs.From).ToArray());

            var fromSource = new HashSet<int>();
            var toDest = new HashSet<int>();

            GetReachable(source, ref fromSource, ref forwards);
            GetReachable(dest, ref toDest, ref reverses);

            var edges = rawEdges
                .Where(e => fromSource.Contains(e.From))
                .Where(e => fromSource.Contains(e.To))
                .Where(e => toDest.Contains(e.From))
                .Where(e => toDest.Contains(e.To))
                .ToArray();

            // initialize distances
            var vertices = new List<Vertex>();
            for (int i = 0; i < vertexCount; i++)
                vertices.Add(new Vertex());
            vertices[source].Distance = 0L;

            // update distances
            for (int i = 0; i < vertices.Count; i++)
            {
                foreach (var e in edges)
                {
                    var from = vertices[e.From];
                    var to = vertices[e.To];

                    if (from.Distance == long.MaxValue)
                        continue;

                    var newDistance = from.Distance + e.Weight;
                    if (to.Distance > newDistance)
                    {
                        to.Distance = newDistance;
                    }
                }
            }

            // check negative cycle
            foreach (var e in edges)
            {
                var from = vertices[e.From];
                var to = vertices[e.To];

                if (from.Distance + e.Weight < to.Distance)
                    return null;
            }

            return vertices[dest].Distance;
        }
    }
}