[C#] 010 - Score Sum Queries
๐ ๋์ด๋ : โญโญ
๐ ์ธ์ด : C#
๐ถ ํ์ด
โ 1๏ผLINQ๋ฅผ ์ด์ฉํ๋ ๋ฐฉ๋ฒ
- ์ฑ์ ์์ ํ์์ค๋ฒ๋ ์ฝ๋. LINQ๋ฅผ ์จ๋ดค๋๋ฐ ์ ์ฒด๋ฅผ ํ์ํ๋๊ฑด ๋นํจ์จ์ ์ด๋ค.
- ๋์ผํ ๊ตฌ์กฐ๋ก for๋ฃจํ๋ก๋ ํ์ด๋ดค๋๋ฐ, ์ํ์๊ฐ์ ๋๊ฐ์ด ๊ฑธ๋ฆฐ๋ค.
using System;
using System.Linq;
namespace atCoder.Contest
{
class Q010_Score_Sum_Queries
{
struct Student
{
public int I, C, P;
}
static void Main()
{
int N = Convert.ToInt32(Console.ReadLine());
Student[] students = new Student[N];
for (int i = 0; i < N; i++)
{
int[] array = Console.ReadLine().Split().Select(Int32.Parse).ToArray();
students[i].C = array[0];
students[i].P = array[1];
students[i].I = i + 1;
}
int Q = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < Q; i++)
{
int[] queryNum = Console.ReadLine().Split().Select(Int32.Parse).ToArray();
int L = (
from student in students
where (student.I >= queryNum[0] && student.I <= queryNum[1]) && student.C == 1
select student.P
).Sum();
int R = (
from student in students
where (student.I >= queryNum[0] && student.I <= queryNum[1]) && student.C == 2
select student.P
).Sum();
Console.WriteLine($"{L} {R}");
}
}
}
}
โญ 2๏ผ๋ฏธ๋ฆฌ ํฉ์ ๊ตฌํด๋๋ ๋ฐฉ๋ฒ
- Q๋ฅผ ๋ฐ์ ๋ ๋งค๋ฒ ๋ฃจํ๋ฅผ ๋์ง ์๋๋ก ๋ฏธ๋ฆฌ ์ ๋ ฅ๋จ๊ณ์์ ํฉ๊ณ๋ฅผ ๊ตฌํด๋๋ค.
- Q๋ฅผ ๋ฐ์ผ๋ฉด (์ต๋๊ตฌ๊ฐ์ ํฉ - ์ต์๊ตฌ๊ฐ์ ํฉ) ์ผ๋ก ํฉ๊ณ๋ฅผ ๋ฃจํ์์ด ๊ตฌํ๋ค.
using System;
using System.Linq;
namespace atCoder.Contest
{
class Q010_Score_Sum_Queries
{
static void Main()
{
int N = Convert.ToInt32(Console.ReadLine());
int[] Lsum = new int[N+1];
int[] Rsum = new int[N+1];
for (int i = 1; i < N+1; i++)
{
int[] array = Console.ReadLine().Split().Select(Int32.Parse).ToArray();
Lsum[i] = Lsum[i - 1];
Rsum[i] = Rsum[i - 1];
if (array[0] == 1) Lsum[i] += array[1];
else if (array[0] == 2) Rsum[i] += array[1];
}
int Q = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < Q; i++)
{
int[] queryNum = Console.ReadLine().Split().Select(Int32.Parse).ToArray();
int L = Lsum[queryNum[1]] - Lsum[queryNum[0]-1];
int R = Rsum[queryNum[1]] - Rsum[queryNum[0]-1];
Console.WriteLine($"{L} {R}");
}
}
}
}
(post-code: 2022-05-05-010)