开始用O(n^2)的dp,然后tle了。
#include <iostream>
#include <cstdio>
#include <cstring>
//tle代码
const int MAX = 3e5 + 5;
char arr[MAX];
int dp[MAX];
int main()
{
scanf("%s", arr + 1);
int lenth = strlen(arr + 1), ans = 0;
for (int i = 1; i <= lenth; ++i)
{
int res = 0;
for (int j = i; j <= lenth; ++j)
{
res = (res * 10 + arr[j] - '0') % 4;
if (res == 0)
{
dp[j] += dp[j - 1] + 1;
dp[j - 1] = 0;
}
else
{
dp[j] += dp[j - 1];
dp[j - 1] = 0;
}
}
}
printf("%d\n", dp[lenth]);
return 0;
}
然后直接用数学方法,扫描一遍字符串,直接判断。
#include <iostream>
#include <cstdio>
const int MAX = 3e5 + 5;
char arr[MAX];
long long res;
int main()
{
scanf("%s", arr + 1);
for (int i = 1; arr[i]; ++i)
{
if (arr[i] % 4 == 0)
res++;
if (i > 1 && (arr[i] + arr[i - 1] * 10) % 4 == 0)
res += i - 1;
}
printf("%I64d\n", res);
return 0;
}