HDU 2050——折线分割平面【递推】

题目传送门

Problem Description

我们看到过很多直线分割平面的题目,今天的这个题目稍微有些变化,我们要求的是n条折线分割平面的最大数目。比如,一条折线可以将平面分成两部分,两条折线最多可以将平面分成7部分,具体如下所示。
在这里插入图片描述

Input

输入数据的第一行是一个整数C,表示测试实例的个数,然后是C 行数据,每行包含一个整数n(0<n<=10000),表示折线的数量。

Output

对于每个测试实例,请输出平面的最大分割数,每个实例的输出占一行。

Sample Input

2
1 2

Sample Output

2
7

分析:

交点决定了射线和线段的条数,进而决定了新增的区域数。当n-1条折线时,区域数为f(n-1)。为了使增加的区域最多,则折线的两边的线段要和n-1条折线的边,即2*(n-1)条线段相交。那么新增的线段数为4*(n-1)射线数为2。但要注意的是,折线本身相邻的两线段只能增加一个区域。

故:
f(n) = f(n-1) + 4(n-1) + 2 - 1【记忆化+打表即可】

【继续优化可得到线性答案】
= f(n-1) + 4(n-1) + 1
= f(n-2) + 4(n-2) + 4(n-1) + 2
……
= f(1) + 4 + 4*2 + …… + 4(n-1) + (n-1)
= 2n2 - n + 1

AC代码:

#include <iostream>
#include <vector>
#include <utility>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <cstdio>
#include <set>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;

#define INF 0X3F3F3F


ll ans[10005];
ll f(ll x) {
    if (ans[x] == 0)
        return ans[x] = 2 * f(x - 1) + 1;
    else
        return ans[x];
}
int main() {
    ans[1] = 2;
    ans[2] = 7;
    for (int i = 2; i <= 10001; i++)
    {
        ans[i] = ans[i - 1] + 4 * i - 3;
    }
    int T;
    while (cin >> T) {
        while (T--) {
            ll n;
            cin >> n;
            cout << ans[n] << endl;
        }
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章