F Find 3-friendly Integers
题目描述
A positive integer is 3-friendly if and only if we can find a continuous substring in its decimal representation, and the decimal integer represented by the substring is a multiple of 3.
For instance:
104 is 3-friendly because “0” is a substring of “104” and 0 mod 3 = 0.
124 is 3-friendly because “12” is a substring of “124” and 12 mod 3 = 0. “24” is also a valid substring.
17 is not 3-friendly because 1 mod 3 != 0, 7 mod 3 != 0, 17 mod 3 != 0.
Note that the substring with leading zeros is also considered legal.
Given two integers L and R, you are asked to tell the number of positive integers x such that L ≤ x ≤ R and x is 3-friendly.
输入描述:
There are multiple test cases. The first line of the input contains an integer T(1 ≤ T ≤ 10000), indicating the number of test cases. For each test case:
The only line contains two integers L, R(1 ≤ L ≤ R ≤ 10^18 ), indicating the query.
输出描述:
For each test case output one line containing an integer, indicating the number of valid x.
示例1
输入
3
4 10
1 20
1 100
输出
3
11
76
题目大意:
如果一个正整数的某个连续子串可以被3整除,那么这个数就被称作对3友好,给定左边界L和右边界R,问在这个区间内有多少个对3友好的数。
题解:
首先我们打表暴力求出前100个数中3友好型数的数量。
要判断一个数字是否为3友好型,可以枚举数字的连续子串,只要有一个子串是3的倍数就可以了。
#include <bits/stdc++.h>
using namespace std;
int check(int n) { // 判断是否是对3友好的数
string s = to_string(n);
for (int i = 0; i < s.length(); i ++)
for (int j = 1; j <= s.length() - i; j ++)
if (stoi(s.substr(i, j)) % 3 == 0) return 1; // 枚举子串判断
return 0;
}
int main() {
int res = 0;
for (int i = 1; i <= 200; i ++) { // 输出1 - 200满足要求的累加和
if (check(i)) res ++;
cout << i << ":" << res << '\n';
}
return 0;
}
根据打表结果我们发现
从89开始后面的每一个数都是3友好型数,所以我们只需要把前1 - 89满足要求数的累加和存入数组,之后的答案只需要求一下和89的差就可以推出。
注意L和R要开long long。
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int res[] = {0,0,0,1,1,1,2,2,2,3,4,4,5,6,6,7,8,8,9,10,11,12,12,13,14,14,15,16,16,17,18,19,20,21,22,23,24,25,26,27,28,28,29,30,30,31,32,32,33,34,35,36,36,37,38,38,39,40,40,41,42,43,44,45,46,47,48,49,50,51,52,52,53,54,54,55,56,56,57,58,59,60,60,61,62,62,63,64,64,65,};
int main() {
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t --) {
ll l, r;
cin >> l >> r;
if (l > 89) l = res[89] + (l - 89) - 1; // 大于89就和89算差得出
else l = res[l - 1];
if (r > 89) r = res[89] + (r - 89); // 大于89就和89算差得出
else r = res[r];
if (r != l) cout << r - l << '\n'; // 用前缀和求差得出答案
else cout << r << '\n';
}
return 0;
}