--- 这里是 cjiaw 的小窝(●'◡'●) ---

正在玩命加载中......

洛谷__P1284 三角形牧场

题目链接:P1284 三角形牧场 - 洛谷


题目大意:

给 n 根木棒,

求:用这些木棒拼成的最大面积,对结果*100,无法构建输出 -1


思路:

假设所有木棒长度之和为sum

(布尔型)表示用个木板能否围成两边长为 的三角形,显然第三条边长就是 sum-i-j ;

转移时分三种情况:

  • 把第个木板放在这条边中:那就要用前个木板围成的三角形,即
  • 把第个木板放在这条边中:
  • 把第个木板放在第三条边中:

作用是判断给定的木棒能拼成的不同方案


代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 2008, mod = 998244353;

int n, m;
int a[N];
bool f[N][N];//能用所给的木棒拼成的两边为true
int s = 0;

//检查能否构成三角形
bool check(int x, int y, int z) {
    if (x + y > z && x + z > y && y + z > x) return 1;
    return 0;
}

//海伦公式计算
double cal(double x, double y, double z) {
    double p = (x + y + z) / 2;
    return sqrt(p * (p - x) * (p - y) * (p - z));
}

void solve() {
   
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        s += a[i];
    }
    
    f[0][0] = 1;//一根木棒不用是合法状态
    for (int k = 1; k <= n; k++) {
        for (int i = s / 2; i >= 0; i--) {
            for (int j = s / 2; j >= 0; j--) {
                if (i - a[k] >= 0 && f[i - a[k]][j]) f[i][j] = 1;
                if (j - a[k] >= 0 && f[i][j - a[k]]) f[i][j] = 1;
            }
        }
    }
    
    double res = -1;
    for (int i = s / 2; i >= 0; i--) {
        for (int j = s / 2; j >= 0; j--) {
            if (!f[i][j]) continue;//所给的木棒不能拼出三角形的两边 就continue
            if (!check(i, j, s - i - j)) continue;
            res = max(res, cal(i, j, s - i - j));
        }
    }
    
    if (res != -1) cout << (int)(res * 100) << endl;
    else cout << res << endl;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int T = 1;
// cin >> T;
    while (T--) solve();
    
    return 0;
}

 

posted @ 2025-11-05 22:26  wwjjw  阅读(10)  评论(0)    收藏  举报