减少执行时间c#算法

Reduce execution time c# algorithm

我正在解决 Kattis' bokforing 问题,其中一个测试用例由于执行时间太长(> 2 秒)而失败。谁能给我一些改进的建议?

class Program
{
    static void Main(string[] args)
    {
        /* Inputs 
            3 5
            SET 1 7
            PRINT 1
            PRINT 2
            RESTART 33
            PRINT 1
         */
        string first = Console.ReadLine();
        int N = Convert.ToInt32(first.Split(" ")[0]);
        int Q = Convert.ToInt32(first.Split(" ")[1]);

        int[] Accounts = new int[N];
        string[] Operations = new string[Q];

        for (int i = 0; i < Operations.Length; i++)
        {
            Operations[i] = Console.ReadLine();
        }

        for (int i = 0; i < Operations.Length; i++)
        {
            string[] op = Operations[i].Split(" ");
            string operation = op[0];

            int accountId = 0;
            int ammont = 0;

            if (operation == "SET")
            {
                accountId = Convert.ToInt32(op[1]);
                ammont = Convert.ToInt16(op[2]);
                Accounts[accountId - 1] = ammont;
            }
            if (operation == "PRINT")
            {
                accountId = Convert.ToInt32(op[1]);
                Console.WriteLine(Accounts[accountId - 1]);
            }
            if (operation == "RESTART")
            {
                ammont = Convert.ToInt16(op[1]);
                for (int j = 0; j <= N - 1; j++)
                {
                    Accounts[j] = ammont;
                }
            }
        }
    }
}

首先,我将推荐的 IO 类 从 FAQ 复制到解决方案中,删除了双循环(不需要循环两次 - 先读取输入然后处理它们)然后主要技巧是使用 Dictionary 而不是数组,因此无需每次手动清除其中所有项目的 it/set 金额:

var scanner = new Scanner();

using(var writer = new BufferedStdoutWriter())
{
    var N = scanner.NextInt();
    var Q = scanner.NextInt();

    var amount = 0;
    var Accounts = new Dictionary<int, int>();

    for (var i = 0; i < Q; i++)
    {
        var s = scanner.Next();
        var accountId = 0;

        if (s == "SET")
        {
            accountId = scanner.NextInt();
            Accounts[accountId] = scanner.NextInt();
        }
        else if (s == "PRINT")
        {
            accountId = scanner.NextInt();

            if (!Accounts.TryGetValue(accountId, out var value))
            {
                value = amount;
            }

            writer.WriteLine(value);
        }
        else if (s == "RESTART")
        {
            amount = scanner.NextInt();
            Accounts = new Dictionary<int, int>();
        }
    }
}