hdu4486 Pen Counts

思路参考自http://blog.csdn.net/yylxid/article/details/8601075

题意:给定一个三角形的周长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

枚举第一条边,再根据第二条边的上下界则可得三角形的个数, 中间还要考虑有俩边或三边相等的情况

 

hdu4486
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>

using namespace std;

int main()
{
    int T, cas, n;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&cas, &n);
        int ans = 0;
        for(int x = 1; x <= n / 3; ++x)//默认枚举最小的那条边, 明显 x <= n / 3;
        {

            int ymin = max(x, n / 2 - x + 1);//求出第二条边的上下界
            int ymax = (n - x) / 2;

            if( x == ymin ) //第一条边等于第二条边
                --ans;

            if(x != ymax && ymax == n - x - ymax) //不是等边三角形 && 第二边等于第三边
                --ans;

            ans += (ymax - ymin + 1) * 2;
        }
        printf("%d %d\n",cas, ans);
    }
    return 0;
}

 

posted @ 2013-04-01 19:18  枕边梦  阅读(302)  评论(0编辑  收藏  举报