uva 11401 - Triangle Counting
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2396
11401 - Triangle Counting
Time limit: 1.000 seconds
Triangle Counting
Input: Standard Input
Output: Standard Output
You are given n rods of length 1, 2…, n. You have to pick any 3 of them & build a triangle. How many distinct triangles can you make? Note that, two triangles will be considered different if they have at least 1 pair of arms with different length.
Input
The input for each case will have only a single positive integer n (3<=n<=1000000). The end of input will be indicated by a case with n<3. This case should not be processed.
Output
For each test case, print the number of distinct triangles you can make.
Sample Input Output for Sample Input
5 8 0 |
3 22 |
Problemsetter: Mohammad Mahmudur Rahman
分析:
递推。
AC代码:
1 // UVa11401 Triangle Counting 2 3 4 #include<iostream> 5 6 using namespace std; 7 8 9 10 long long f[1000010]; // int存不下 11 12 int main() { 13 14 f[3] = 0; 15 16 for(long long x = 4; x <= 1000000; x++) 17 18 f[x] = f[x-1] + ((x-1)*(x-2)/2 - (x-1)/2)/2; // 递推 19 20 21 22 int n; 23 24 while(cin >> n) { 25 26 if(n < 3) break; 27 28 cout << f[n] << endl; 29 30 } 31 32 return 0; 33 34 }