【发布时间】:2015-10-20 21:13:18
【问题描述】:
使用在线自动化测试系统 Kattis,我面临的挑战(在 C# 中)创建一个电话号码列表,然后找出其中任何一个是前缀还是另一个。
(参见:https://ncpc.idi.ntnu.no/ncpc2007/ncpc2007problems.pdf,任务 A)
提供答案相对容易,但无论我如何尝试,我都无法逃脱得到结果:超出时间限制,还有一些进一步的信息表明运行程序需要超过 4 秒(通过自动程序)。
我曾多次尝试从头开始重写它,并且我已经尝试了我可以在互联网上找到的所有现有建议。我发现自己完全不知所措,主要是因为最终我无法确定到底出了什么问题。
This code 是在类似(但未解决)thread 上提出的,但并没有发挥作用 - 但这是迄今为止我见过的最好的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhoneList
{
class Program
{
static void Main(string[] args)
{
// Save number of test cases.
var numTestCases = int.Parse(Console.ReadLine());
// Do this for each test case.
for (int i = 0; i < numTestCases; i++)
{
// Save number of phone numbers.
var numPhoneNumbers = int.Parse(Console.ReadLine());
// Save all phonenumbers in the list.
var phoneNumbersList = new List<string>();
for (int j = 0; j < numPhoneNumbers; j++)
{
string number = Console.ReadLine().Trim();
// Add to list.
phoneNumbersList.Add(number);
}
// Write output.
if (phoneNumbersList.All(n => !phoneNumbersList.Except(new[] { n }).Any(o => o.StartsWith(n))))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
}
}
有什么建议吗?
【问题讨论】:
-
如果这段代码可以正常工作,这可能属于Code Review
-
对您的电话号码列表进行排序。然后你只需要比较
n项和n-1项,直到找到违反规则的项或到达列表末尾。 -
是的,这让我通过了第二次测试!但是在第三次测试中仍然触发了 Time Limit Exceeded... 我用 * Check update in OP * 替换了 LINQ 查询 *
-
在您的
if语句中,使用break跳出循环。找到一个错误号码后,无需浪费时间检查其余号码。 -
糟糕,忘记休息是愚蠢的。虽然没有任何区别......仍然卡在程序超时的第三个测试用例中......是的,我发现了两个关于完全相同问题的线程,但没有解决方案。但是它们已经很老了。
标签: c# performance time