题解:P6726 [COCI 2015/2016 #5] POPLAVA

· · 题解

题目描述

给你两个数 n,x,求使用 1\sim n 个柱子让组成的柱状图容量为 x。

Solution

一眼看过去,这道题类似于水桶效应

我们举一个例子:\

```latex * * * * ** * *** * **** * ***** * ****** ******** ``` 这个柱状图的水不能溢过第 $1$ 列,所以第 $2$ 列至第 $7$ 列的容量依次为 $6,5,4,3,2,1$,使用等差数列求和公式可知,这个柱状图容量为 $\frac{7 \times 6}{2}$。把这个公式变成关于 $n$ 的式子,我们就可以得到: > $1\sim n$ 的柱子组成的柱状图最大容量为 $\frac{(n-1)\cdot(n-2)}{2}$。 然后就可以特判输入的 $n,x$ 是否能建立柱状图。 --- 那如何求建立的柱状图容量为 $x$ 呢? 还是以上面的例子说明:\ 当我们去掉一根柱子时,相应的会减少 $(7-$“这个柱子长度”$)$,也就是 $(n-1)-h_{i}$。 用 $tmp$ 存这个柱状图需要删去多少容量,遍历 $n-2\sim 1$($n$ 和 $n-1$ 是两边),我们一次一次删去 $h_{i} \le tmp$ 的柱子,相反的就是删去 $n-1-h_{i}$ 的柱子。 最后我们把删去的柱子放在最后即可。 # Code ```cpp #include <bits/stdc++.h> using namespace std; #define endl "\n" #define sp " " #define Ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); using ll = long long; using ull = unsigned long long; using ld = long double; ll n, x, tmp; bool vis[1000005]; int main() { Ios; cin >> n >> x; if (n <= 2) cout << -1 << endl,exit(0); tmp = (n - 1) * (n - 2) / 2-x; if (tmp < 0) cout << -1 << endl, exit(0); for (ll i = n - 2;i >= 1;i--) if (tmp >= i) tmp -= i, vis[n - 1 - i] = 1; cout << n - 1 << sp; vis[n - 1] = 1; for (ll i = 1;i <= n;i++) if (!vis[i]) cout << i << sp; vis[n - 1] = 0; for (ll i = n;i >= 1;i--) if (vis[i]) cout << i << sp; return 0; } ```