a659中等固定最大邊,累加新增三角形
CPE:Triangle Counting (UVa 11401)
由三角不等式推導每個最大邊的貢獻。
解題思路
每組邊長唯一寫成 a<b<c。固定最大邊 c 後,只需 a+b>c;對每個 b,a 從 c−b+1 到 b−1,合法數為 max(0,2b−c−1)。依 b 加總形成 1,3,5,… 或 2,4,6,… 的級數。
將級數化簡,最大邊 c 的新增數量為 floor((c−2)²/4)。因此 answer[c]=answer[c−1]+floor((c−2)²/4),先讀完直到 n<3 的查詢,再預算到最大 n。所有三邊互異,等號 a+b=c 是退化形必須排除;答案用 64 位元。
Step-by-step animation
示意:n=5
步驟 1 / 3
最大邊 3
1+2=3,沒有非退化三角形。
1
2
3
- 新增
- 0
- 累計
- 0
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> queries;
int n, limit = 2;
while (cin >> n && n >= 3) {
queries.push_back(n);
limit = max(limit, n);
}
vector<long long> answer(limit + 1);
for (long long c = 3; c <= limit; c++)
answer[c] = answer[c - 1] + (c - 2) * (c - 2) / 4;
for (int x : queries)
cout << answer[x] << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。