题意:给定一个三角形的周长n, 问能组成的三角形的个数。若三边均不等,则个数加一
分析:假定三角形的三条边长分别为x , y , z 其中 x <= y <= z
若x已知, 则可得 y + z = n - x
令 z - y = t , 则 0 <= t < x (俩边之差小于第三边)
将t 代入上式可得 y = (n - x - t) / 2;
则 (n - 2x) / 2 < y <= (n - x) / 2 即 n / 2 - x + 1 <= y <= (n - x) / 2
枚举第一条边,再根据第二条边的上下界则可得三角形的个数, 中间还要考虑有俩边或三边相等的情况.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int p;
int m,n;
int x,y,z;//x<=y<=z
int ymin,ymax;
int ans;
scanf(" %d",&p);
while(p--)
{
ans = 0;
scanf(" %d %d",&m,&n);
printf("%d ",m);
for(x = 1;x<=n/3;x++)
{
ymin = max(n/2 -x + 1,x);
ymax = (n-x)/2;
if(x == ymin) ans--;//第一条边和第二条边相等时减一
if(x!=ymax && ymax == n - x - ymax) ans--;//不是等边三角形,并且第二边和第三边相等时减一
ans += (ymax - ymin + 1)*2;
}
printf("%d\n",ans);
}
return 0;
}