AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC334-D Reindeer and Sleigh
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("4 3");
WillReturn.Add("5 3 11 8");
WillReturn.Add("16");
WillReturn.Add("7");
WillReturn.Add("1000");
//3
//1
//4
}
else if (InputPattern == "Input2") {
WillReturn.Add("6 6");
WillReturn.Add("1 2 3 4 5 6");
WillReturn.Add("1");
WillReturn.Add("2");
WillReturn.Add("3");
WillReturn.Add("4");
WillReturn.Add("5");
WillReturn.Add("6");
//1
//1
//2
//2
//2
//3
}
else if (InputPattern == "Input3") {
WillReturn.Add("2 2");
WillReturn.Add("1000000000 1000000000");
WillReturn.Add("200000000000000");
WillReturn.Add("1");
//2
//0
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static long[] mRunSumArr;
static void Main()
{
List<string> InputList = GetInputList();
long[] RArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();
Array.Sort(RArr);
mRunSumArr = (long[])RArr.Clone();
for (long I = 1; I <= mRunSumArr.GetUpperBound(0); I++) {
mRunSumArr[I] += mRunSumArr[I - 1];
}
foreach (string EachStr in InputList.Skip(2)) {
long X = long.Parse(EachStr);
int ResultInd = ExecNibunhou_LowerOrEqual_Max(X, mRunSumArr);
if (ResultInd == -1) {
Console.WriteLine(0);
}
else {
Console.WriteLine(ResultInd + 1);
}
}
}
// 二分法で、Val以下で最大の値を持つ、添字を返す
static int ExecNibunhou_LowerOrEqual_Max(long pVal, long[] pArr)
{
// 最後の要素が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;
}
}
解説
累積和を求めておいて、二分探索してます。