【发布时间】:2021-03-30 07:01:24
【问题描述】:
这是函数 f(T,k) 的代码,其中
f(T,0)=∑(from i=1 to i≤len(T)) T[i], where len(T) is length of array T.
f(T,k)=∑(from i=1 to i≤len(T)) ∑(from j=i to j≤len(T)) f(T[i...j],k-1), for k>0, where len(T) is length
of array T and T[i...j] is sub-array of T with elements form the i-th to the j-th position (T[i],T[i+1],...,T[j])
这是一个递归函数,我需要降低复杂度,但我不知道如何。
有人可以帮帮我吗?
这是问题文本:
1000000007名玩家参加本次比赛,获胜者由随机选择决定。为了使选择随机,该公司为选择该球员制定了严格的规则。首先他们用从 0 到 1000000006 的识别号给玩家编号。然后他们选择包含 N 个元素和数字 k 的数组 A。然后他们将获胜者定义为识别号为 f (A, k) mod (100000007) 的玩家
#include <iostream>
#include <vector>
using namespace std;
int N,k,a;
vector<int>A;
int fja(vector<int>A,int k){
long long suma=0;
if(k==0){// If k==0 calculate the first said function
for(auto it=A.begin();it!=A.end();it++)suma=(suma+(*it))%(1000000007);//Moduo is there because suma is very big
return suma;
}else{//If k>0 calculate the second function
int duzina=A.size();//duzina is length of A (T)
for(int i=0;i<duzina;i++){//Going through the first and second sum of second function
for(int j=i;j<duzina;j++){
vector<int>b(A.begin()+i,A.begin()+j+1);//Creating new vector (array) to pass it into the new function call
suma=(suma+fja(b,k-1))%(1000000007);//Moduo is there because suma is very big
}
}
return suma;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>N>>k; //Number of elements and k
for(int i=0;i<N;i++){
cin>>a;
A.push_back(a);//All the elements
}
cout<<fja(A,k);
}
【问题讨论】:
-
您发布的代码有什么问题?
-
@AlanBirtles 对于 N 和 k 的大输入来说太慢了。我想降低时间复杂度。
-
@Sip_ 你能提供 N 和 k 的限制吗?还有时间限制。
-
N 和 k 的大值究竟是什么?你期望什么运行时间?你看到了什么运行时?您是否启用了编译器优化?
-
将
fja改为采用一对迭代器而不是一个向量将避免复制数据的需要
标签: c++ algorithm recursion time-complexity