Triangle Counting
题目大意:给定n,n >= 3,求用1,2,3,...,n-1,n这些木棒能拼出的三角形个数
尝试设三条边为x,y,z,发现仅通过x + y < z, x - y < z无法找到解题方向
不妨再加一些附加条件,设x为最大边长度,就有x - y < z < x,只需计算此时x,y,z取值个数,加和即可
y = 1时无解;y = 2时z = x - 1;y = 3时z = x - 1, x - 2;....y = i时,z有i - 1种取值
共有Σ(i = 0 to x - 2)i种取值,即(n - 2) * (n - 1) / 2
不难发现存在z = y的情况,去掉即可,即y > x/2时,z = x,于是有x - 1 - ([x / 2] + 1) + 1 = x - [x / 2] - 1 = [(x + 1) / 2] - 1 = [(x - 1) / 2]
每个三角形考虑了两边,最后答案/2
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 #include <queue> 7 #include <vector> 8 #define min(a, b) ((a) < (b) ? (a) : (b)) 9 #define max(a, b) ((a) > (b) ? (a) : (b)) 10 #define abs(a) ((a) < 0 ? (-1 * (a)) : (a)) 11 inline void swap(long long &a, long long &b) 12 { 13 long long tmp = a;a = b;b = tmp; 14 } 15 inline void read(long long &x) 16 { 17 x = 0;char ch = getchar(), c = ch; 18 while(ch < '0' || ch > '9') c = ch, ch = getchar(); 19 while(ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar(); 20 if(c == '-') x = -x; 21 } 22 23 const long long INF = 0x3f3f3f3f; 24 const long long MAXN = 1000000 + 10; 25 26 long long f[MAXN], n; 27 28 int main() 29 { 30 for(register long long i = 1;i <= 1000000;++ i) 31 f[i] = f[i - 1] + ((((i - 2) * (i - 1) >> 1) - ((i - 1) >> 1)) >> 1); 32 while(scanf("%lld", &n) != EOF && n >= 3) 33 { 34 printf("%lld ", f[n]); 35 } 36 return 0; 37 }