我正在嘗試在線裁判的經典子集總和問題。然而,這次的差別是,n < = 30,所以最大操作可以達到30 * 2^30。我已經在下面有一些工作代碼。但是,程序的時間限制是1秒,我的程序在0.5到1.1秒之間徘徊。這導致了TLE,儘管我試圖儘可能地加快我的代碼速度。你們有沒有關於我如何能夠進一步加快和優化我的代碼的提示?提前致謝。優化C++代碼
#include <iostream>
#include <cstdio>
using namespace std;
unsigned power(unsigned x, unsigned y){ //pow function
unsigned sum=x;
for (int i=1;i<=y-1;i++)
sum*=x;
return sum;
}
int main(){
unsigned t, n, p, sum, sum2, tmpsum=0;
unsigned bars[32];
bool found;
scanf("%u", &t);
while (t--){
tmpsum=0;
found=false;
scanf("%u %u", &n, &p);
for (int i=0;i<p;i++){
scanf("%u",&bars[i]);
tmpsum+=bars[i];
}
if (tmpsum<n)found=false;
unsigned end=power(2,p)-1; //counting from the end and from the start
for (unsigned i=0;i<power(2,p)&&tmpsum>=n;i++){ //counting from 1 to 2^n in binary
sum=0;
sum2=0;
for (unsigned j=0;j<p;j++){
if (i&(1<<j))
sum+=bars[j];
if (end&(1<<j)) //counting from the end and start at the same time
{sum2+=bars[j];end--;}
}
if (sum==n||sum2==n)
{found=true;break;}
}
cout<<(found==true?"YES":"NO")<<endl;
}
}
您應該在http://codereview.stackexchange.com/上發佈此問題。 – 2013-02-18 09:00:17
人,指數函數可以大大提高。在這裏尋找更多的信息:http://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms/ – AraK 2013-02-18 09:01:14