Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

How do i select numbers with certain indexes from a List in C# with Linq and find their SUM

So there is a list of elements(for example: 1, 9, 6, 5, 4, 7, 10). I have numbers x,y,k. x- starting index,
y- limit index, k- by how much x is increasing itself. For example: x=2, y=6, k =2. first step x is 2, second x is 4, third x is 6. Indexing starts from 0. I want to find the Sum of numbers from the given List whose indexes are all values of x in the given steps for all queries(number of queries is q, n is the number of elements in a List, "dani" represents the list of elements, a is the list where the calculated sums go, "rez" represents the sum).

Restrains: 1≤N≤200000 1≤Q≤200000 1≤ki≤N 1≤xi≤yi≤N

Time limit is 1.5s.

My question is is there a faster way than using a for or while loop to calculate the sum?

    long n = long.Parse(Console.ReadLine());
    var dani = Console.ReadLine().Split().Select(long.Parse).ToList();
    long q = long.Parse(Console.ReadLine());
    List<long> a = new List<long>();
    for(int i=0;i<q;i++)
    {
        var s = Console.ReadLine().Split();
        int x = int.Parse(s[0]);
        int y = int.Parse(s[1]);
        int k = int.Parse(s[2]);
        x--;
        y--;

        long rez = 0;
        while(true)
        {
            rez += dani[x];
            x += k;
            if (x > y)
                break;
        }
        
    }
    for(int i=0;i<a.Count;i++)
        Console.WriteLine(a[i]);
question from:https://stackoverflow.com/questions/65871252/how-do-i-select-numbers-with-certain-indexes-from-a-list-in-c-sharp-with-linq-an

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...