0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

paiza 区間和の計算 LINQ使うとランタイムエラーになる。(C#)

0
Last updated at Posted at 2023-03-13

Aランクレベルアップメニューの「区間和の計算」でLINQを使って配列に格納すると、ランタイムエラーになってしまう。原因はLINQが重いから??

Sample.csの書き方の場合、「区間和の計算」テスト3で100000もの数値を配列に入れる際にランタイムエラーになる。

Sample2.csの場合は無事通過。なんでかわかる方はコメントお願いします。

Sample.cs
using System;
using System.Linq;
using System.Collections.Generic;

class Practice
{
    static void Main()
    {

        int count = int.Parse(Console.ReadLine());

        // こいつが重い?
        int[] text = Console.ReadLine().Split().Select(_ => int.Parse(_)).ToArray();

        int c = int.Parse(Console.ReadLine());

        int[] sn = new int[count];

        for (int i = 0; i < count; i++) {

            if (i == 0)
                sn[i] = text[0];
            else
                sn[i] = sn[i - 1] + text[i];
        }

        for (int i = 0; i < c; i++) {

            int[] line = Console.ReadLine().Split().Select(_ => int.Parse(_)).ToArray();

            int min = line[0];
            int max = line[1];
            
            if (min == 0)
                Console.WriteLine(sn[max]);
            else
                Console.WriteLine(sn[max] - sn[min - 1]);
        }
    }
}

Sample2.cs
using System;
using System.Linq;
using System.Collections.Generic;

class Practice
{
    static void Main()
    {

        int count = int.Parse(Console.ReadLine());

        // 一度string配列で受け取って使う時にint型にキャスト
        string[] text = Console.ReadLine().Split(' ');

        int c = int.Parse(Console.ReadLine());

        int[] sn = new int[count];

        for (int i = 0; i < count; i++) {

            if (i == 0)
                sn[i] = int.Parse(text[0]);
            else
                sn[i] = sn[i - 1] + int.Parse(text[i]);
        }

        for (int i = 0; i < c; i++) {

            int[] line = Console.ReadLine().Split().Select(_ => int.Parse(_)).ToArray();

            int min = line[0];
            int max = line[1];
            
            if (min == 0)
                Console.WriteLine(sn[max]);
            else
                Console.WriteLine(sn[max] - sn[min - 1]);
        }
    }
}
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?