我的方法是先將陣列 num[] 由小到大排序:
For MAX=(陣列大小-1) To 2
若: num[m]+num[n]>num[MAX] 則: num[m]+num[n+1]>num[MAX] 且 num[m+1]+num[n]>num[MAX] 算出對應 (m,n)的個數
否則: 還是算出對應(m,n)的個數~.~
End For
看了半天看不出錯在哪~
與正確輸出不相符(line:35)
您的答案為: 15
正確答案為: 16
int sumfromitoj(int i, int j) //i<=j
{
int sum=0;
if (i>j) return -9999999;
else {
for (int k=i; k<=j; k++)
{
sum += k;
}
return sum;
}
}
int count_remains_of_the_row(int num[], int original_sum_m_n, int n, int MAX)
{
int cnt=0;
for (int i=n+1; i<MAX; i++)
{
if (original_sum_m_n + num[i] > num[MAX]) cnt++;
}
if (n>=MAX) return 0;
else return cnt+count_remains_of_the_row(num, original_sum_m_n+num[n+1], n+1, MAX);
}
/*
Given: sorted_num[size-1] the last(largest) number of sorted array sorted_num[]
For MAX=size-1 To MAX=2 Do the Following thing
For (m=0; m<MAX; m++)
For (n=m+1; n<MAX; n++)
If sorted_num[m] + sorted_num[n] > num[MAX] Then
Count += Count_On_MAP(m,n,MAX) to Count_On_MAP(m,MAX-1,MAX)
Else
Count += RemainCount_On_MAP(m,n,MAX)
End For
End for
End For
*/
int num_of_polygons(int sorted_num[], int size)
{
int count=0, count_the_pass=0, count_the_row=0;
int MAX;
for (MAX=size-1; MAX>=2; MAX--)
{
int m=0,n=0;
for (m=0; m<MAX; m++)
{
for (n=m+1; n<MAX; n++)
{
if (sorted_num[m]+sorted_num[n] > sorted_num[MAX]) {
count_the_row += sumfromitoj(1,MAX-n); break;
}
else {
count_the_row += count_remains_of_the_row(sorted_num, sorted_num[m]+sorted_num[n], n, MAX );
}
}
count_the_pass += count_the_row;
count_the_row = 0;
}
count += count_the_pass;
count_the_pass = 0;
}
return count;
}
int main()
{
int num[105],i;
stringstream ss;
string s;
while ( getline(cin, s) )
{
ss.str(s);
i=0;
while (ss >> num[i]) {
i++;
if (num[i-1]==0) i--;
if ( i>105 ) { cout << "Too many numbers\n"; break; }
}
if (i==0) break;
else {
qsort(num,i,sizeof(int),compare);
cout << num_of_polygons(num, i) << endl;
ss.clear();
}
}
return 0;
}