Luogu CF1472C Long Jumps题解

【题目分析】

本题有两个方法,

方法一:每一个位置可得的分分别求出,打擂找出最大(可得部分分)

方法二:从后往前求可得的分数,以避免一些不必要的重复。

【设计程序】

方法一:

 1 #include<bits/stdc++.h>
 2 #include<iostream>
 3 #include<stdio.h>
 4 #include<cstdio>
 5 #include<queue>
 6 using namespace std;
 7 const int N = 2 * 1e5 + 5;
 8 int a[N];
 9 int n;
10 long long score(int x)//求这个位置出发可得的分
11 {
12     long long ans = 0;
13     while(x <= n)//当x还在n的范围中时
14     {
15         ans += a[x];//加这个位置的值
16         x += a[x];//把x标到下一个位置
17     }
18     return ans;//返回得分
19 }
20 int main()
21 {
22     int p;
23     scanf ("%d", &p);//输入组数
24     while (p--)
25     {
26         long long maxn = 0;
27         scanf ("%d", &n);//输入数据个数
28         for (int i = 1;i <= n; i++)//输入数据
29             scanf ("%d", a + i);
30         for (int i = 1;i <= n; i++)//从每一个位置开始
31             maxn = max(maxn, score(i));//求最大值
32         printf ("%d\n", maxn);//输出最大值
33     }
34     return 0;
35 }

 

方法二:

 1 #include<bits/stdc++.h>
 2 #include<iostream>
 3 #include<stdio.h>
 4 #include<cstdio>
 5 #include<queue>
 6 using namespace std;
 7 const int N = 2 * 1e5 + 5;
 8 int a[N];
 9 long long b[N];//b[i]表示从i出发可得的分数
10 int n;
11 int main()
12 {
13     int p;
14     scanf ("%d", &p); //输入组数
15     while (p--)
16     {
17         scanf ("%d", &n); //输入数据个数
18         for (int i = 1;i <= n; i++)//输入数据
19             scanf ("%d", a + i);
20         for (int i = n;i >= 1; i--)
21         {
22             if (i + a[i] > n)
23             //如果后一个位置在n的范围外
24                 b[i] = a[i];//此位置的得分为本位置的值
25             else//如果在n中
26                 b[i] = a[i] + b[i + a[i]];
27                 //本位置的值加上下个位置的得分
28         }
29         long long maxn = b[1];
30         for (int i = 2;i <= n; i++)//打擂找最大
31             maxn = max(maxn, b[i]);
32         printf ("%d\n", maxn);//输出最大值
33     }
34     return 0;
35 }

 

【调试代码】
1. 测试样例
2. 自测数据(特殊值,边界值)

数据:

4

5

0 0 0 0 0

3

3 2 1

1

1000

5

1 1 1 1 1

 

posted @ 2022-01-08 13:13  睡不醒的凪  阅读(20)  评论(0)    收藏  举报