蒟蒻来讲题,还望大家喜。若哪有问题,大家尽可提!
Hello, 大家好哇!本初中生蒟蒻今天以AtCoder Beginner Contest 285的D题——Change Usernames为例,给大家讲解一下判断图中存在闭环的常用方法!
===========================================================================================
Problem Statement
In the world where Takahashi lives, a week has N N N days.
Takahashi, the king of the Kingdom of AtCoder, assigns “weekday” or “holiday” to each day of week. The assignments should be the same for all weeks. At least one day of week should be assigned “holiday”.
Under such conditions, the productivity of the i i i-th day of week is defined by a sequence A A A of length N N N as follows:
Find the maximum productivity per week when the assignments are chosen optimally.
Here, the productivity per week refers to the sum of the productivities of the
1 1 1-st, 2 2 2-nd, …, and N N N-th day of week.
Constraints
Input
The input is given from Standard Input in the following format:
N
A1
A2
…
AN
Output
Print the answer as an integer.
Sample Input 1
7
10 10 1 1 1 1 1
Sample Output 1
50
For example, we can assign “holiday” to the
2-nd and 4-th day of week and “weekday” to the rest to achieve a productivity of 50 per week:
It is impossible to make the productivity per week 51 51 51 or greater.
Sample Input 2
10
200000000 500000000 1000000000 800000000 100000000 80000000 600000 900000000 1 20
Sample Output 2
5100000000
Sample Input 3
20
38 7719 21238 2437 8855 11797 8365 32285 10450 30612 5853 28100 1142 281 20537 15921 8945 26285 2997 14680
Sample Output 3
236980
这道题我们有可用动态规划了,先来找一下规律:
如果把两个假期之间的天数设为 t t t,则:
因此推出 ∑ i = 1 d A ⌊ i + 1 2 ⌋ \sum_{i = 1}^{d}A_{\left \lfloor \frac{i + 1}{2} \right \rfloor} ∑i=1dA⌊2i+1⌋,我们把它赋值为 g i g_{i} gi
#include
#include
#define int long long
using namespace std;
const int N = 5e3 + 10;
int yxc_n;
int yxc_a[N];
int yxc_f[N][N];
int yxc_g[N];
signed main()
{
cin >> yxc_n;
for (int i = 1; i <= yxc_n; i ++)
cin >> yxc_a[i];
for (int i = 1; i <= yxc_n; i ++)
yxc_g[i] = yxc_g[i - 1] + yxc_a[(i + 1) / 2];
for (int i = 0; i <= yxc_n; i ++)
for (int j = 0; j <= yxc_n; j ++)
yxc_f[i][j] = -1e16;
yxc_f[1][0] = 0;
for (int i = 1; i < yxc_n; i ++)
for (int j = 0; j <= yxc_n; j ++)
{
if(yxc_f[i][j] < 0) continue;
yxc_f[i + 1][j + 1] = max(yxc_f[i + 1][j + 1], yxc_f[i][j]);
yxc_f[i + 1][0] = max(yxc_f[i + 1][0], yxc_f[i][j] + yxc_g[j]);
}
int yxc_res = 0;
for (int i = 0; i <= yxc_n; i ++)
yxc_res = max(yxc_res, yxc_f[yxc_n][i] + yxc_g[i]);
cout << yxc_res << endl;
return 0;
}