如果给定了n数,我如何找到可能的三角形总数?有没有什么方法可以在O(n^3)时间内做到这一点?
我正在考虑三角形的a+b>c,b+c>a和a+c>b条件。
发布于 2011-11-20 20:42:58
我已经设计出了一个算法,运行时间为O(n^2 lgn)。我认为这是正确的..。代码在C++中被命名为...
int Search_Closest(A,p,q,n) /*Returns the index of the element closest to n in array
A[p..q]*/
{
if(p<q)
{
int r = (p+q)/2;
if(n==A[r])
return r;
if(p==r)
return r;
if(n<A[r])
Search_Closest(A,p,r,n);
else
Search_Closest(A,r,q,n);
}
else
return p;
}
int no_of_triangles(A,p,q) /*Returns the no of triangles possible in A[p..q]*/
{
int sum = 0;
Quicksort(A,p,q); //Sorts the array A[p..q] in O(nlgn) expected case time
for(int i=p;i<=q;i++)
for(int j =i+1;j<=q;j++)
{
int c = A[i]+A[j];
int k = Search_Closest(A,j,q,c);
/* no of triangles formed with A[i] and A[j] as two sides is (k+1)-2 if A[k] is small or equal to c else its (k+1)-3. As index starts from zero we need to add 1 to the value*/
if(A[k]>c)
sum+=k-2;
else
sum+=k-1;
}
return sum;
}希望这对你有帮助......
https://stackoverflow.com/questions/8110538
复制相似问题