Triangle Formation(大约就是暴力求解吧)

Triangle Formation
Time Limit:25000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u

Gym 100735D
Description
standard input/output
Statements
You are given N wooden sticks. Your task is to determine how many triangles can be made from the given sticks without breaking them. Each stick can be used in at most one triangle.

Input
The first line of each test case contains the number of sticks N. (1 ≤ N ≤ 15)

The second line of each test case contains N integers leni that are the lengths of the sticks. (1 ≤ leni ≤ 109).

Output
Output single integer R – the maximal number of triangles.

Sample Input
Input
2
1 1
Output
0
Input
3
2 2 2
Output
1
Input
6
2 2 3 4 5 6
Output
2

先从小到大排序,枚举出每一种情况,判断能否成立,一旦能组成三角形,就标记这支小木棒用过了,代码能过,但还是有一些复杂。欢迎在评论中提出优化后的代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
    int n, i, j, k, cnt=0;
    int a[20];
    int vis[20];
    memset(a, 0, sizeof(a));
    memset(vis, 0, sizeof(vis));
    cin>>n;
    for(i=0; i<n; i++)
        cin>>a[i];
    sort(a, a+n);
    for(i=0; i<=n-3; i++)
    {
        for(j=i+1; j<=n-2; j++)
        {
            for(k=j+1; k<=n-1; k++)
            {
                if(a[i]+a[j]>a[k]&&vis[i]==0&&vis[j]==0&&vis[k]==0)
                {
                    ++cnt;
                    vis[i]=1;
                    vis[j]=1;
                    vis[k]=1;
                    break;
                }
            }
        }
    }
    cout<<cnt;
    return 0;
}

你可能感兴趣的:(暴力求解法)