【发布时间】:2015-08-26 06:23:27
【问题描述】:
这个问题是正在进行的竞赛的一部分,我已经解决了这个问题数据集的 75%,但 25% 给了我 TLE。我在问为什么它给 TLE 我确定我的复杂性是 O(n*n)
问题:
由 N 个小写英文字母组成的字符串 S。我们准备了一个由all non empty substrings of the string S组成的列表L。
现在他问你Q问题。对于第 i 个问题,您需要计算从列表 L 中准确选择 Ki 相等字符串的方法的数量
例如:
String = ababa
L = {"a", "b", "a", "b", "a", "ab", "ba", "ab", "ba", "aba", "bab", "aba", "abab", "baba", "ababa"}.
k1 = 2: There are seven ways to choose two equal strings ("a", "a"), ("a", "a"), ("a", "a"), ("b", "b"), ("ab", "ab"), ("ba", "ba"), ("aba", "aba").
k2 = 1: We can choose any string from L (15 ways).
k3 = 3: There is one way to choose three equal strings - ("a", "a", "a").
k4 = 4: There are no four equal strings in L .
Question LINK
我的方法
我正在对 IT 进行 TRIE 并 计算和数组 F[i],其中 F[i] 表示 i 等于字符串出现的次数。 我的 TRIE:
static class Batman{
int value;
Batman[] next = new Batman[26];
public Batman(int value){
this.value = value;
}
}
我的插入功能
public static void Insert(String S,int[] F , int start){
Batman temp = Root;
for(int i=start;i<S.length();i++){
int index = S.charAt(i)-'a';
if(temp.next[index]==null){
temp.next[index] = new Batman(1);
F[1]+=1;
}else{
temp.next[index].value+=1;
int xx = temp.next[index].value;
F[xx-1]-=1;
F[xx]+=1;
// Calculating The Frequency of I equal Strings
}
temp = temp.next[index];
}
}
我的主要功能
public static void main(String args[] ) throws java.lang.Exception {
Root = new Batman(0);
int n = in.nextInt();
int Q = in.nextInt();
String S = in.next();
int[] F = new int[n+1];
for(int i=0;i<n;i++)
Insert(S,F,i);
long[] ans = new long[n+1];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
ans[i]+= F[j]*C[j][i]; // C[n][k] is the Binomial Coffecient
ans[i]%=mod;
}
}
while(Q>0){
Q--;
int cc = in.nextInt();
long o =0;
if(cc<=n) o=ans[cc];
System.out.println(o+" "+S.length());
}
}
为什么我的方法是给 TLE,因为时间复杂度是 O(N*N),而字符串的长度是 NWorking CODE
【问题讨论】:
-
请记住
10n*n和1000000n*n都是O(n*n)。 -
@azurefrog 我听不懂,请解释一下
-
在考虑"Big O" notation 时,尤其是当您尝试calculate it for your program 时,您需要记住,当n 很小时(如您的示例中),二次项将主导总时间比 n 大时要少得多。仅仅因为你的程序是 O(n*n) 并不意味着它会运行得很快,只是它的运行时间的缩放会随着输入大小的平方而变化。
标签: java algorithm data-structures tree trie