AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
DPL_1_D: Longest Increasing Subsequence
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q075 最長増加部分列 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_D&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("6");
WillReturn.Add("10");
WillReturn.Add("30");
WillReturn.Add("50");
WillReturn.Add("20");
WillReturn.Add("40");
WillReturn.Add("60");
//4
}
else if (InputPattern == "Input2") {
WillReturn.Add("3");
WillReturn.Add("1");
WillReturn.Add("1");
WillReturn.Add("1");
//1
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
long[] AArr = InputList.Skip(1).Select(pX => long.Parse(pX)).ToArray();
long Answer = ClassDeriveStrictLISLength.DeriveLength(AArr);
Console.WriteLine(Answer);
}
}
#region ClassDeriveStrictLISLength
// LIS(狭義単調増加)の長さを返す
internal class ClassDeriveStrictLISLength
{
// 引数 long型の列挙
// 戻り値 LISの長さ
internal static long DeriveLength(IEnumerable<long> pEnum)
{
// LISの最終値の最小値[LISの長さ] なDP表
var DPSortedList = new SortedList<long, long>();
foreach (long EachVal in pEnum) {
if (DPSortedList.Count == 0) {
DPSortedList[1] = EachVal;
continue;
}
long UpsertKeyInd = ExecNibunhou(DPSortedList, EachVal);
long CurrUB = DPSortedList.Count - 1;
var Keys = DPSortedList.Keys;
// 更新する位置によって分岐
if (UpsertKeyInd <= CurrUB) {
DPSortedList[Keys[(int)UpsertKeyInd]] = EachVal;
}
else {
long PrevKey = Keys[(int)CurrUB];
DPSortedList[PrevKey + 1] = EachVal;
}
}
if (DPSortedList.Count == 0) {
return 0;
}
int UB = DPSortedList.Count - 1;
return DPSortedList.Keys[UB];
}
// 二分法で、引数の値を設定する、キーの配列の添字を返す
private static long ExecNibunhou(SortedList<long, long> pDPSortedList, long pTargetVal)
{
int UB = pDPSortedList.Count - 1;
var Keys = pDPSortedList.Keys;
// 最小値以下の場合
if (pTargetVal <= pDPSortedList[Keys[0]]) {
return 0;
}
// 最大値より大きい場合
if (pTargetVal > pDPSortedList[Keys[UB]]) {
return UB + 1;
}
int L = 0;
int R = UB;
while (L + 1 < R) {
int Mid = (L + R) / 2;
if (pDPSortedList[Keys[Mid]] < pTargetVal) {
L = Mid;
}
else {
R = Mid;
}
}
return R;
}
}
#endregion
解説
SortedListジェネリックで
LISの最終値の最小値[LISの長さ] を管理する動的計画法で
二分法を使ってます。