【发布时间】:2015-09-02 08:26:34
【问题描述】:
我有以下代码,但处理 BigInteger 类型的 52957 个输入需要 20 秒。这是我要解决的问题https://www.hackerearth.com/problem/algorithm/girlfriends-demands/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace girldfriends_demands
{
class Program
{
private static string inputString = String.Empty;
private static int testCases=0;
private static BigInteger[,] indexArray;
static void Main(string[] args)
{
initialize();
printDemand();
Console.ReadLine();
}
private static void initialize()
{
inputString = Console.ReadLine();
testCases = int.Parse(Console.ReadLine());
indexArray = new BigInteger[testCases, 2];
for (int i = 0; i < testCases; i++)
{
string[] tokens = Console.ReadLine().Split();
indexArray[i, 0] = BigInteger.Parse(tokens[0]);
indexArray[i, 1] = BigInteger.Parse(tokens[1]);
}
}
private static void printDemand()
{
char[] convertedString = inputString.ToCharArray();
for (int i = 0; i < testCases; i++)
{
BigInteger length=inputString.Length;
BigInteger startf, endf; ;
BigInteger.DivRem(indexArray[i, 0] - 1,length,out startf);
BigInteger.DivRem(indexArray[i, 1]-1,length,out endf);
char c=convertedString[((int)startf)];
char e=convertedString[((int)endf)];
if(c==e)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
}
请说明如何降低代码的时间复杂度。此程序获取字符串中指定位置的字母,如果相同则打印 true,否则为 false。在循环之前计算范围也无济于事
【问题讨论】:
-
你也有示例输入集吗? Console.WriteLine 速度很慢 - 在循环结束时写入内存/转储输出更快。
-
@OndrejSvejdar 这是示例输入
-
20 秒?这太荒谬了。你到底想做什么?为什么不直接比较两个字符串,而不是将它们转换为
BigInteger,然后做复杂的数学运算呢?您正在做大约一百万件不必要的事情(为什么将inputString转换为char[]?为什么一次将所有数据加载到内存中而不是逐行处理?为什么要让事情如此痛苦的程序化?你来自 Pascal背景? -
什么是 DivRem。它是分治算法吗?
-
@Luaan 必须比较字符串的特定字符,并且该字符由输入中的索引指定
标签: c# console-application time-complexity