原题链接:
题目描述:
This is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.
An array bb of length mm is good if for all ii the ii-th element is greater than or equal to ii. In other words, bb is good if and only if bi≥ibi≥i for all ii (1≤i≤m1≤i≤m).
You are given an array aa consisting of nn positive integers. Find the number of pairs of indices (l,r)(l,r), where 1≤l≤r≤n1≤l≤r≤n, such that the array [al,al+1,…,ar][al,al+1,…,ar] is good.
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2⋅1051≤t≤2⋅105). Description of the test cases follows.
The first line of each test case contains an integer nn (1≤n≤2⋅1051≤n≤2⋅105), the length of the array aa.
The second line of each test case contains nn space-separated integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), representing the array aa.
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, print the number of suitable pairs of indices.
题目大意:
给定一个长度为n的正整数数组,数组下标起始为1,定义good数组为数组中每个ai满足ai >= i,
请问题目给出的数组有多少个子数组满足good数组的要求。(子数组单独拿出来之后下标从1开始)。
解题思路:
设dp[i]为以ai结尾能获得的good子数组的数量。
状态转移:
当a[i] >= i时,很显然dp[i] = dp[i - 1] + 1;
否则dp[i]最大也不会超过a[i],应该为dp[i - 1] + 1和a[i]之间的小者。
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 2e5 + 10;
const int INF = 0x3fffffff;
ll n, a[maxn], dp[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
int t;
cin >> t;
while(t--)
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
dp[i] = 0;
}
ll ans = 0;
for (int i = 1; i <= n; i++)
{
if(a[i] >= i)
dp[i] = dp[i - 1] + 1;
else
dp[i] = min(a[i], dp[i - 1] + 1);
ans += dp[i];
}
cout << ans << endl;
}
return 0;
}