結果

問題 No.1640 簡単な色塗り
ユーザー 👑 terry_u16terry_u16
提出日時 2021-08-06 22:39:17
言語 C#
(.NET 8.0.203)
結果
AC  
実行時間 259 ms / 2,000 ms
コード長 26,394 bytes
コンパイル時間 8,259 ms
コンパイル使用メモリ 146,924 KB
実行使用メモリ 52,448 KB
最終ジャッジ日時 2023-09-12 02:40:47
合計ジャッジ時間 24,768 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 74 ms
31,284 KB
testcase_01 AC 71 ms
28,920 KB
testcase_02 AC 75 ms
29,060 KB
testcase_03 AC 74 ms
30,924 KB
testcase_04 AC 141 ms
46,560 KB
testcase_05 AC 154 ms
52,448 KB
testcase_06 AC 75 ms
28,800 KB
testcase_07 AC 75 ms
29,256 KB
testcase_08 AC 75 ms
29,076 KB
testcase_09 AC 71 ms
28,932 KB
testcase_10 AC 169 ms
41,340 KB
testcase_11 AC 152 ms
39,272 KB
testcase_12 AC 141 ms
38,400 KB
testcase_13 AC 253 ms
50,156 KB
testcase_14 AC 259 ms
50,304 KB
testcase_15 AC 118 ms
35,436 KB
testcase_16 AC 130 ms
37,152 KB
testcase_17 AC 219 ms
47,256 KB
testcase_18 AC 83 ms
30,700 KB
testcase_19 AC 139 ms
38,012 KB
testcase_20 AC 168 ms
42,788 KB
testcase_21 AC 147 ms
39,084 KB
testcase_22 AC 80 ms
30,304 KB
testcase_23 AC 177 ms
41,828 KB
testcase_24 AC 98 ms
32,720 KB
testcase_25 AC 139 ms
40,340 KB
testcase_26 AC 200 ms
46,052 KB
testcase_27 AC 114 ms
35,064 KB
testcase_28 AC 245 ms
47,484 KB
testcase_29 AC 195 ms
45,856 KB
testcase_30 AC 77 ms
31,488 KB
testcase_31 AC 149 ms
48,792 KB
testcase_32 AC 136 ms
46,528 KB
testcase_33 AC 98 ms
40,964 KB
testcase_34 AC 122 ms
44,780 KB
testcase_35 AC 97 ms
39,096 KB
testcase_36 AC 75 ms
33,508 KB
testcase_37 AC 79 ms
34,636 KB
testcase_38 AC 137 ms
47,336 KB
testcase_39 AC 86 ms
36,140 KB
testcase_40 AC 86 ms
36,312 KB
testcase_41 AC 122 ms
44,868 KB
testcase_42 AC 90 ms
37,004 KB
testcase_43 AC 90 ms
39,368 KB
testcase_44 AC 89 ms
37,096 KB
testcase_45 AC 85 ms
35,352 KB
testcase_46 AC 77 ms
32,072 KB
testcase_47 AC 73 ms
30,952 KB
testcase_48 AC 139 ms
47,728 KB
testcase_49 AC 71 ms
30,072 KB
testcase_50 AC 72 ms
28,812 KB
testcase_51 AC 72 ms
29,224 KB
testcase_52 AC 239 ms
52,284 KB
testcase_53 AC 242 ms
52,176 KB
07_evil_01.txt AC 512 ms
74,716 KB
07_evil_02.txt AC 785 ms
233,016 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
  Determining projects to restore...
  Restored /home/judge/data/code/main.csproj (in 124 ms).
.NET 向け Microsoft (R) Build Engine バージョン 17.0.0-preview-21470-01+cb055d28f
Copyright (C) Microsoft Corporation.All rights reserved.

  プレビュー版の .NET を使用しています。https://aka.ms/dotnet-core-preview をご覧ください
  main -> /home/judge/data/code/bin/Release/net6.0/main.dll
  main -> /home/judge/data/code/bin/Release/net6.0/publish/

ソースコード

diff #

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Text;
using YukicoderContest308.Problems;

namespace YukicoderContest308.Problems
{
    public class ProblemE : ProblemBase
    {
        public ProblemE() : base(false) { }

        [MethodImpl(MethodImplOptions.AggressiveOptimization)]
        protected override void SolveEach(IOManager io)
        {
            var n = io.ReadInt();
            var ab = new (int a, int b)[n];
            var list = Enumerable.Repeat(0, n).Select(_ => new SortedSet<int>()).ToArray();

            for (int i = 0; i < n; i++)
            {
                var a = io.ReadInt();
                var b = io.ReadInt();
                a--;
                b--;
                ab[i] = (a, b);
                list[a].Add(i);
                list[b].Add(i);
            }

            var segTree = new SegmentTree<MinInt>(list.Select((l, index) => new MinInt(l.Count, index)).ToArray());

            var results = new int[n];

            for (int i = 0; i < n; i++)
            {
                var minint = segTree.QueryAll();

                if (minint.Value == 0)
                {
                    io.WriteLine("No");
                    return;
                }

                var op = list[minint.Index].Min;
                var other = ab[op].a == minint.Index ? ab[op].b : ab[op].a;

                list[minint.Index].Remove(op);
                list[other].Remove(op);
                results[op] = minint.Index;
                segTree[other] = new MinInt(segTree.Query(other, other + 1).Value - 1, other);
                segTree[minint.Index] = new MinInt(int.MaxValue, minint.Index);
            }

            io.WriteLine("Yes");

            for (int i = 0; i < results.Length; i++)
            {
                io.WriteLine(results[i] + 1);
            }
        }

        readonly struct MinInt : IMonoid<MinInt>
        {
            public readonly int Value;
            public readonly int Index;

            public MinInt Identity => new MinInt(int.MaxValue, -1);

            public MinInt(int value, int index)
            {
                Value = value;
                Index = index;
            }

            public MinInt Merge(MinInt other) => Value < other.Value ? this : other;
            public override string ToString() => Value.ToString();
            public static implicit operator int(MinInt value) => value.Value;
        }


        public interface ISemigroup<TSet>
        {
            public TSet Merge(TSet other);
        }

        public interface IMonoid<TSet> : ISemigroup<TSet>
        {
            public TSet Identity { get; }
        }

        public interface IMonoidWithAct<TMonoid, TOperator> : IMonoid<TOperator>
            where TMonoid : IMonoid<TMonoid>
            where TOperator : IMonoid<TOperator>
        {
            public TMonoid Act(TMonoid monoid);
        }


        public class SegmentTree<T> where T : struct, IMonoid<T>
        {
            // 1-indexed
            protected readonly T[] _data;

            public int Length { get; }
            protected Span<T> Leaves => _data.AsSpan(HalfLength, Length);
            protected int HalfLength => _data.Length >> 1;

            /// <summary>
            /// 単位元で初期化します。
            /// </summary>
            public SegmentTree(int n) : this(n, default(T).Identity) { }

            /// <summary>
            /// 指定した値で初期化します。
            /// </summary>
            public SegmentTree(int n, T initialValue)
            {
                if (n < 0)
                {
                    throw new ArgumentOutOfRangeException();
                }

                Length = n;
                _data = new T[1 << (CeilPow2(n) + 1)];
                _data.AsSpan(HalfLength, Length).Fill(initialValue);
                Build();
            }

            /// <summary>
            /// 指定したデータ列で初期化します。
            /// </summary>
            public SegmentTree(ReadOnlySpan<T> values)
            {
                Length = values.Length;
                _data = new T[1 << (CeilPow2(values.Length) + 1)];
                values.CopyTo(Leaves);
                Build();
            }

            public virtual T this[int index]
            {
                get => Leaves[index];
                set
                {
                    Leaves[index] = value;
                    index += HalfLength;
                    while ((index >>= 1) > 0)
                    {
                        _data[index] = _data[(index << 1) + 0].Merge(_data[(index << 1) + 1]);
                    }
                }
            }

            public T Query(Range range) => Query(range.Start, range.End);

            public T Query(Index left, Index right) => Query(left.GetOffset(Length), right.GetOffset(Length));

            public virtual T Query(int left, int right)
            {
                if (unchecked((uint)left > (uint)Length || (uint)right > (uint)Length || left > right))
                {
                    throw new ArgumentOutOfRangeException();
                }

                var sumL = default(T).Identity;
                var sumR = default(T).Identity;
                left += HalfLength;
                right += HalfLength;

                while (left < right)
                {
                    if ((left & 1) > 0)
                    {
                        sumL = sumL.Merge(_data[left++]);
                    }
                    if ((right & 1) > 0)
                    {
                        sumR = _data[--right].Merge(sumR);
                    }
                    left >>= 1;
                    right >>= 1;
                }

                return sumL.Merge(sumR);
            }

            public T QueryAll() => _data[1];

            private void Build()
            {
                var parents = HalfLength;
                _data.AsSpan(parents + Length).Fill(default(T).Identity);
                for (int i = parents - 1; i >= 0; i--)
                {
                    _data[i] = _data[(i << 1) + 0].Merge(_data[(i << 1) + 1]);
                }
            }

            /// <summary>
            /// [l, r)が条件を満たす最大のrを求めます。
            /// </summary>
            public int FindMaxRight(Index left, Predicate<T> predicate) => FindMaxRight(left.GetOffset(Length), predicate);

            /// <summary>
            /// [l, r)が条件を満たす最大のrを求めます。
            /// </summary>
            public virtual int FindMaxRight(int left, Predicate<T> predicate)
            {
                // 単位元は条件式を満たす必要がある
                Debug.Assert(predicate(default(T).Identity));

                if (unchecked((uint)left > Length))
                {
                    throw new ArgumentOutOfRangeException();
                }
                else if (left == Length)
                {
                    return Length;
                }

                var right = left + HalfLength;
                var sum = default(T).Identity;

                do
                {
                    right >>= BitOperations.TrailingZeroCount(right);
                    var merged = sum.Merge(_data[right]);
                    if (!predicate(merged))
                    {
                        return DownSearch(right, sum, predicate);
                    }

                    sum = merged;
                    right++;
                } while ((right & -right) != right);

                return Length;

                int DownSearch(int right, T sum, Predicate<T> predicate)
                {
                    while (right < HalfLength)
                    {
                        right <<= 1;
                        var merged = sum.Merge(_data[right]);
                        if (predicate(merged))
                        {
                            sum = merged;
                            right++;
                        }
                    }
                    return right - HalfLength;
                }
            }

            /// <summary>
            /// [l, r)が条件を満たす最小のlを求めます。
            /// </summary>
            public int FindMinLeft(Index right, Predicate<T> predicate) => FindMinLeft(right.GetOffset(Length), predicate);

            /// <summary>
            /// [l, r)が条件を満たす最小のlを求めます。
            /// </summary>
            public virtual int FindMinLeft(int right, Predicate<T> predicate)
            {
                // 単位元は条件式を満たす必要がある
                Debug.Assert(predicate(default(T).Identity));

                if (unchecked((uint)right > Length))
                {
                    throw new ArgumentOutOfRangeException();
                }
                else if (right == 0)
                {
                    return 0;
                }

                var left = right + HalfLength;
                var sum = default(T).Identity;

                do
                {
                    left--;
                    left >>= BitOperations.TrailingZeroCount((1 << BitOperations.Log2((uint)left)) | ~left);

                    var merged = _data[left].Merge(sum);
                    if (!predicate(merged))
                    {
                        return DownSearch(left, sum, predicate);
                    }

                    sum = merged;
                } while ((left & -left) != left);

                return 0;

                int DownSearch(int left, T sum, Predicate<T> predicate)
                {
                    while (left < HalfLength)
                    {
                        left = (left << 1) + 1;
                        var merged = _data[left].Merge(sum);
                        if (predicate(merged))
                        {
                            sum = merged;
                            left--;
                        }
                    }
                    return left + 1 - HalfLength;
                }
            }

            protected static int CeilPow2(int n)
            {
                var m = (uint)n;
                if (m <= 1)
                {
                    return 0;
                }
                else
                {
                    return BitOperations.Log2(m - 1) + 1;
                }
            }
        }


    }
}

namespace YukicoderContest308
{
    class Program
    {
        static void Main(string[] args)
        {
            IProblem question = new ProblemE();
            using var io = new IOManager(Console.OpenStandardInput(), Console.OpenStandardOutput());
            question.Solve(io);
        }
    }
}

#region Base Class

namespace YukicoderContest308.Problems
{
    public interface IProblem
    {
        string Solve(string input);
        void Solve(IOManager io);
    }

    public abstract class ProblemBase : IProblem
    {
        protected bool HasMultiTestCases { get; }

        protected ProblemBase(bool hasMultiTestCases) => HasMultiTestCases = hasMultiTestCases;

        public string Solve(string input)
        {
            var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(input));
            var outputStream = new MemoryStream();
            using var manager = new IOManager(inputStream, outputStream);

            Solve(manager);
            manager.Flush();

            outputStream.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(outputStream);
            return reader.ReadToEnd();
        }

        public void Solve(IOManager io)
        {
            var tests = HasMultiTestCases ? io.ReadInt() : 1;

            for (var t = 0; t < tests; t++)
            {
                SolveEach(io);
            }
        }

        protected abstract void SolveEach(IOManager io);
    }
}

#endregion

#region Utils

namespace YukicoderContest308
{
    public class IOManager : IDisposable
    {
        private readonly BinaryReader _reader;
        private readonly StreamWriter _writer;
        private bool _disposedValue;
        private byte[] _buffer = new byte[1024];
        private int _length;
        private int _cursor;
        private bool _eof;

        const char ValidFirstChar = '!';
        const char ValidLastChar = '~';

        public IOManager(Stream input, Stream output)
        {
            _reader = new BinaryReader(input);
            _writer = new StreamWriter(output) { AutoFlush = false };
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private char ReadAscii()
        {
            if (_cursor == _length)
            {
                _cursor = 0;
                _length = _reader.Read(_buffer);

                if (_length == 0)
                {
                    if (!_eof)
                    {
                        _eof = true;
                        return char.MinValue;
                    }
                    else
                    {
                        ThrowEndOfStreamException();
                    }
                }
            }

            return (char)_buffer[_cursor++];
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public char ReadChar()
        {
            char c;
            while (!IsValidChar(c = ReadAscii())) { }
            return c;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public string ReadString()
        {
            var builder = new StringBuilder();
            char c;
            while (!IsValidChar(c = ReadAscii())) { }

            do
            {
                builder.Append(c);
            } while (IsValidChar(c = ReadAscii()));

            return builder.ToString();
        }

        public int ReadInt() => (int)ReadLong();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long ReadLong()
        {
            long result = 0;
            bool isPositive = true;
            char c;

            while (!IsNumericChar(c = ReadAscii())) { }

            if (c == '-')
            {
                isPositive = false;
                c = ReadAscii();
            }

            do
            {
                result *= 10;
                result += c - '0';
            } while (IsNumericChar(c = ReadAscii()));

            return isPositive ? result : -result;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private Span<char> ReadChunk(Span<char> span)
        {
            var i = 0;
            char c;
            while (!IsValidChar(c = ReadAscii())) { }

            do
            {
                span[i++] = c;
            } while (IsValidChar(c = ReadAscii()));

            return span.Slice(0, i);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public double ReadDouble() => double.Parse(ReadChunk(stackalloc char[32]));

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public decimal ReadDecimal() => decimal.Parse(ReadChunk(stackalloc char[32]));

        public int[] ReadIntArray(int n)
        {
            var a = new int[n];
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = ReadInt();
            }
            return a;
        }

        public long[] ReadLongArray(int n)
        {
            var a = new long[n];
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = ReadLong();
            }
            return a;
        }

        public double[] ReadDoubleArray(int n)
        {
            var a = new double[n];
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = ReadDouble();
            }
            return a;
        }

        public decimal[] ReadDecimalArray(int n)
        {
            var a = new decimal[n];
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = ReadDecimal();
            }
            return a;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Write<T>(T value) => _writer.Write(value.ToString());

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void WriteLine<T>(T value) => _writer.WriteLine(value.ToString());

        public void WriteLine<T>(IEnumerable<T> values, char separator)
        {
            var e = values.GetEnumerator();
            if (e.MoveNext())
            {
                _writer.Write(e.Current.ToString());

                while (e.MoveNext())
                {
                    _writer.Write(separator);
                    _writer.Write(e.Current.ToString());
                }
            }

            _writer.WriteLine();
        }

        public void WriteLine<T>(T[] values, char separator) => WriteLine((ReadOnlySpan<T>)values, separator);
        public void WriteLine<T>(Span<T> values, char separator) => WriteLine((ReadOnlySpan<T>)values, separator);

        public void WriteLine<T>(ReadOnlySpan<T> values, char separator)
        {
            for (int i = 0; i < values.Length - 1; i++)
            {
                _writer.Write(values[i]);
                _writer.Write(separator);
            }

            if (values.Length > 0)
            {
                _writer.Write(values[^1]);
            }

            _writer.WriteLine();
        }

        public void Flush() => _writer.Flush();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool IsValidChar(char c) => ValidFirstChar <= c && c <= ValidLastChar;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool IsNumericChar(char c) => ('0' <= c && c <= '9') || c == '-';

        private void ThrowEndOfStreamException() => throw new EndOfStreamException();

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _reader.Dispose();
                    _writer.Flush();
                    _writer.Dispose();
                }

                _disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }

    public static class UtilExtensions
    {
        public static bool ChangeMax<T>(ref this T value, T other) where T : struct, IComparable<T>
        {
            if (value.CompareTo(other) < 0)
            {
                value = other;
                return true;
            }
            return false;
        }

        public static bool ChangeMin<T>(ref this T value, T other) where T : struct, IComparable<T>
        {
            if (value.CompareTo(other) > 0)
            {
                value = other;
                return true;
            }
            return false;
        }

        public static void SwapIfLargerThan<T>(ref this T a, ref T b) where T : struct, IComparable<T>
        {
            if (a.CompareTo(b) > 0)
            {
                (a, b) = (b, a);
            }
        }

        public static void SwapIfSmallerThan<T>(ref this T a, ref T b) where T : struct, IComparable<T>
        {
            if (a.CompareTo(b) < 0)
            {
                (a, b) = (b, a);
            }
        }

        public static void Sort<T>(this T[] array) where T : IComparable<T> => Array.Sort(array);
        public static void Sort<T>(this T[] array, Comparison<T> comparison) => Array.Sort(array, comparison);
    }

    public static class CollectionExtensions
    {
        private class ArrayWrapper<T>
        {
#pragma warning disable CS0649
            public T[] Array;
#pragma warning restore CS0649
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<T> AsSpan<T>(this List<T> list)
        {
            return Unsafe.As<ArrayWrapper<T>>(list).Array.AsSpan(0, list.Count);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<T> GetRowSpan<T>(this T[,] array, int i)
        {
            var width = array.GetLength(1);
            return MemoryMarshal.CreateSpan(ref array[i, 0], width);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<T> GetRowSpan<T>(this T[,,] array, int i, int j)
        {
            var width = array.GetLength(2);
            return MemoryMarshal.CreateSpan(ref array[i, j, 0], width);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<T> GetRowSpan<T>(this T[,,,] array, int i, int j, int k)
        {
            var width = array.GetLength(3);
            return MemoryMarshal.CreateSpan(ref array[i, j, k, 0], width);
        }

        public static void Fill<T>(this T[] array, T value) => array.AsSpan().Fill(value);
        public static void Fill<T>(this T[,] array, T value) => MemoryMarshal.CreateSpan(ref array[0, 0], array.Length).Fill(value);
        public static void Fill<T>(this T[,,] array, T value) => MemoryMarshal.CreateSpan(ref array[0, 0, 0], array.Length).Fill(value);
        public static void Fill<T>(this T[,,,] array, T value) => MemoryMarshal.CreateSpan(ref array[0, 0, 0, 0], array.Length).Fill(value);
    }

    public static class SearchExtensions
    {
        struct LowerBoundComparer<T> : IComparer<T> where T : IComparable<T>
        {
            public int Compare(T x, T y) => 0 <= x.CompareTo(y) ? 1 : -1;
        }

        struct UpperBoundComparer<T> : IComparer<T> where T : IComparable<T>
        {
            public int Compare(T x, T y) => 0 < x.CompareTo(y) ? 1 : -1;
        }

        // https://trsing.hatenablog.com/entry/2019/08/27/211038
        public static int GetGreaterEqualIndex<T>(this ReadOnlySpan<T> span, T inclusiveMin) where T : IComparable<T> => ~span.BinarySearch(inclusiveMin, new UpperBoundComparer<T>());
        public static int GetGreaterThanIndex<T>(this ReadOnlySpan<T> span, T exclusiveMin) where T : IComparable<T> => ~span.BinarySearch(exclusiveMin, new LowerBoundComparer<T>());
        public static int GetLessEqualIndex<T>(this ReadOnlySpan<T> span, T inclusiveMax) where T : IComparable<T> => ~span.BinarySearch(inclusiveMax, new LowerBoundComparer<T>()) - 1;
        public static int GetLessThanIndex<T>(this ReadOnlySpan<T> span, T exclusiveMax) where T : IComparable<T> => ~span.BinarySearch(exclusiveMax, new UpperBoundComparer<T>()) - 1;
        public static int GetGreaterEqualIndex<T>(this Span<T> span, T inclusiveMin) where T : IComparable<T> => ((ReadOnlySpan<T>)span).GetGreaterEqualIndex(inclusiveMin);
        public static int GetGreaterThanIndex<T>(this Span<T> span, T exclusiveMin) where T : IComparable<T> => ((ReadOnlySpan<T>)span).GetGreaterThanIndex(exclusiveMin);
        public static int GetLessEqualIndex<T>(this Span<T> span, T inclusiveMax) where T : IComparable<T> => ((ReadOnlySpan<T>)span).GetLessEqualIndex(inclusiveMax);
        public static int GetLessThanIndex<T>(this Span<T> span, T exclusiveMax) where T : IComparable<T> => ((ReadOnlySpan<T>)span).GetLessThanIndex(exclusiveMax);

        public static int BoundaryBinarySearch(Predicate<int> predicate, int ok, int ng)
        {
            while (Math.Abs(ok - ng) > 1)
            {
                var mid = (ok + ng) / 2;
                if (predicate(mid))
                {
                    ok = mid;
                }
                else
                {
                    ng = mid;
                }
            }
            return ok;
        }

        public static long BoundaryBinarySearch(Predicate<long> predicate, long ok, long ng)
        {
            while (Math.Abs(ok - ng) > 1)
            {
                var mid = (ok + ng) / 2;
                if (predicate(mid))
                {
                    ok = mid;
                }
                else
                {
                    ng = mid;
                }
            }
            return ok;
        }

        public static BigInteger BoundaryBinarySearch(Predicate<BigInteger> predicate, BigInteger ok, BigInteger ng)
        {
            while (BigInteger.Abs(ok - ng) > 1)
            {
                var mid = (ok + ng) / 2;
                if (predicate(mid))
                {
                    ok = mid;
                }
                else
                {
                    ng = mid;
                }
            }
            return ok;
        }

        public static double BoundaryBinarySearch(Predicate<double> predicate, double ok, double ng, double eps = 1e-9, int loopLimit = 1000)
        {
            var count = 0;

            while (Math.Abs(ok - ng) > eps && count++ < loopLimit)
            {
                var mid = (ok + ng) * 0.5;
                if (predicate(mid))
                {
                    ok = mid;
                }
                else
                {
                    ng = mid;
                }
            }

            return (ok + ng) * 0.5;
        }

        public static double Bisection(Func<double, double> f, double a, double b, double eps = 1e-9, int loopLimit = 100)
        {
            double mid = (a + b) / 2;
            var fa = f(a);

            if (fa * f(b) >= 0)
            {
                throw new ArgumentException("f(a)とf(b)は異符号である必要があります。");
            }

            for (int i = 0; i < loopLimit; i++)
            {
                var fmid = f(mid);
                var sign = fa * fmid;

                if (sign < 0)
                {
                    b = mid;
                }
                else if (sign > 0)
                {
                    a = mid;
                    fa = fmid;
                }
                else
                {
                    return mid;
                }

                mid = (a + b) / 2;

                if (Math.Abs(b - a) < eps)
                {
                    break;
                }
            }
            return mid;
        }
    }
}

#endregion
0