AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC172-C Tsundoku
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("3 4 240");
WillReturn.Add("60 90 120");
WillReturn.Add("80 150 80 150");
//3
}
else if (InputPattern == "Input2") {
WillReturn.Add("3 4 730");
WillReturn.Add("60 90 120");
WillReturn.Add("80 150 80 150");
//7
}
else if (InputPattern == "Input3") {
WillReturn.Add("5 4 1");
WillReturn.Add("1000000000 1000000000 1000000000 1000000000 1000000000");
WillReturn.Add("1000000000 1000000000 1000000000 1000000000");
//0
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
long K = wkArr[2];
long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();
int UB_A = AArr.GetUpperBound(0);
long[] BArr = InputList[2].Split(' ').Select(pX => long.Parse(pX)).ToArray();
int UB_B = BArr.GetUpperBound(0);
// Bの累積和を求めておく
long[] BArrRunSum = (long[])BArr.Clone();
for (int I = 1; I <= UB_B; I++) {
BArrRunSum[I] += BArrRunSum[I - 1];
}
// Aでどこまで読むかを全探索
long ARunSum = 0;
long Answer = 0;
for (int I = -1; I <= UB_A; I++) {
if (I >= 0) { // Aを全く読まない場合
ARunSum += AArr[I];
}
long Rest = K - ARunSum;
long AnswerKouho;
if (Rest > 0) {
int BInd = ExecNibunhou_LowerOrEqual_Max(Rest, BArrRunSum);
AnswerKouho = I + 1 + BInd + 1;
}
else if (Rest == 0) {
AnswerKouho = I + 1;
}
else {
break;
}
Answer = Math.Max(Answer, AnswerKouho);
}
Console.WriteLine(Answer);
}
// 二分法で、Val以下で最大の値を持つ、添字を返す
static int ExecNibunhou_LowerOrEqual_Max(long pVal, long[] pArr)
{
if (pArr.Length == 0) return -1;
// 最後の要素がVal以下の特殊ケース
if (pVal >= pArr.Last()) {
return pArr.GetUpperBound(0);
}
// 最初の要素がVal超えの特殊ケース
if (pVal < pArr[0]) {
return -1;
}
int L = 0;
int R = pArr.GetUpperBound(0);
while (L + 1 < R) {
int Mid = (L + R) / 2;
if (pArr[Mid] <= pVal) {
L = Mid;
}
else {
R = Mid;
}
}
return L;
}
}
解説
Bの累積和を求めておいてから、
Aの選択数を0から全て試しつつ、Bが何冊読めるかを二分探索してます。