给定整数N , K和M ,任务是找到大于N的第K个数字,该数字的总和可被M整除。
例子:
Input: N = 6, K = 5, M = 5
Output: 32
Explanation:
The number greater than N = 6 with the sum of their digits divisible by 5 are {14, 19, 23, 28, 32, …}. The Kth number i.e., the 5th number is 32.
Input: N = 40, K = 4, M = 5
Output: 55
Explanation:
The number greater than N = 40 with the sum of their digits divisible by 5 are {41, 46, 50, 55, …}. The Kth number i.e., the 4th number is 55.
天真的方法:最简单的方法是检查每个大于N的数字,如果其位数之和可被M整除,则将计数器增加1 。继续检查数字,直到计数器等于K为止。
时间复杂度: O(K)
辅助空间: O(1)
高效的方法:这个想法是使用 动态编程 和二进制搜索。请按照以下步骤解决问题:
- 首先,创建一个递归存储的函数以查找小于或等于S且具有被M整除的数字之和的整数总数,如下所示:
The dp transitions will be:
dp(S, index, sum, tight, M) = dp(index+1, (sum+i)%M, tight, M) where,
- S is given limit for which all numbers smaller than or equal to S with the sum of digits divisible by M needs to be found.
- index is the current index for which a digit needs to be placed.
- sum takes the values from 0 to 4.
- Base condition is, if index becomes greater than the length of S and sum is divisible by M, return 1.
- M is the divisor.
If the previous digit already placed such that it becomes smaller than S then
- tight will become equal to 0.
- i will iterate from 0 to 9.
If all the previous digits match with the corresponding digits in S, then
- tight will become 1, which denotes that the number is still not become smaller than S.
- i will iterate from 0 to digit S[index].
- 现在使用二进制搜索,下限为N + 1 ,上限为某个大整数。
- 初始化一个剩余的变量,用于存储小于或等于N的总数,其位数之和可被M整除。
- 找到下限和上限的中点,然后使用上面的dp函数找到小于或等于其数字之和可被M整除的中点。说的对。
- 如果left + K等于right ,则将答案更新为中点并将上限设置为中点– 1 。
- 否则,如果left + K小于right,则将上限设置为midpoint-1 。
- 如果left + K大于right,则将下限设置为中点+1 。
- 下限小于或等于上限时,重复上述步骤。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Initialize dp array
int dp[100000][100][2];
// Function to find the numbers <= S
// having digits sum divisible by M
int solve(string s, int index, int sum,
int tight, int z)
{
// Base Case
if (index >= s.size())
{
if (sum % z == 0)
return 1;
return 0;
}
// Visited state
if (dp[index][sum][tight] != -1)
return dp[index][sum][tight];
// Store answer
int ans = 0;
// If number still does not
// become smaller than S
if (tight == 1)
{
// Find limit
int l = s[index] - '0';
// Iterate through all
// the digits
for(int i = 0; i <= l; i++)
{
// If current digit is limit
if (i == l)
{
ans += solve(s, index + 1,
(sum + i) % z, 1, z);
}
// Number becomes smaller than S
else {
ans += solve(s, index + 1,
(sum + i) % z, 0, z);
}
}
}
else
{
// If number already becomes
// smaller than S
for(int i = 0; i <= 9; i++)
ans += solve(s, index + 1,
(sum + i) % z, 0, z);
}
// Return and store the answer
// for the current state
return dp[index][sum][tight] = ans;
}
// Function to find the Kth number
// > N whose sum of the digits is
// divisible by M
int search(int n, int k, int z)
{
// Initialize lower limit
int low = n + 1;
// Initialize upper limit
int high = 1e9;
// Mask dp states unvisited
memset(dp, -1, sizeof(dp));
// Numbers <= N except 0 with
// digits sum divisible by M
int left = solve(to_string(n),
0, 0, 1, z) - 1;
// Initialize answer with -1
int ans = -1;
while (low <= high)
{
// Calculate mid
int mid = low + (high - low) / 2;
// Mark dp states unvisited
memset(dp, -1, sizeof(dp));
// Numbers < mid with digits
// sum divisible by M
int right = solve(to_string(mid),
0, 0, 1, z) - 1;
// If the current mid is
// satisfy the condition
if (left + k == right)
{
// Might be the answer
ans = mid;
// Update upper limit
high = mid - 1;
}
else if (left + k < right)
{
// Update upper limit
high = mid - 1;
}
else
{
// Update lower limit
low = mid + 1;
}
}
// Return the answer
return ans;
}
// Driver Code
int main()
{
// Given N, K, and M
int N = 40;
int K = 4;
int M = 2;
// Function Call
cout << search(N, K, M) << endl;
}
// This code is contributed by bolliranadheer
Java
// Java program for the above approach
import java.util.*;
public class Main {
static int dp[][][];
// Function to find the Kth number
// > N whose sum of the digits is
// divisible by M
public static int search(
int n, int k, int z)
{
// Initialize dp array
dp = new int[100000 + 1][z][2];
// Initialize lower limit
int low = n + 1;
// Initialize upper limit
int high = Integer.MAX_VALUE / 2;
// Mask dp states unvisited
clear();
// Numbers <= N except 0 with
// digits sum divisible by M
int left = solve(n + "", 0,
0, 1, z)
- 1;
// Initialize answer with -1
int ans = -1;
while (low <= high) {
// Calculate mid
int mid = low + (high - low) / 2;
// Mark dp states unvisited
clear();
// Numbers < mid with digits
// sum divisible by M
int right = solve(mid + "", 0,
0, 1, z)
- 1;
// If the current mid is
// satisfy the condition
if (left + k == right) {
// Might be the answer
ans = mid;
// Update upper limit
high = mid - 1;
}
else if (left + k < right) {
// Update upper limit
high = mid - 1;
}
else {
// Update lower limit
low = mid + 1;
}
}
// Return the answer
return ans;
}
// Function to find the numbers <= S
// having digits sum divisible by M
public static int solve(
String s, int index, int sum,
int tight, int z)
{
// Base Case
if (index >= s.length()) {
if (sum % z == 0)
return 1;
return 0;
}
// Visited state
if (dp[index][sum][tight] != -1)
return dp[index][sum][tight];
// Store answer
int ans = 0;
// If number still does not
// become smaller than S
if (tight == 1) {
// Find limit
int l = s.charAt(index) - '0';
// Iterate through all
// the digits
for (int i = 0; i <= l; i++) {
// If current digit is limit
if (i == l) {
ans += solve(s, index + 1,
(sum + i) % z,
1, z);
}
// Number becomes smaller than S
else {
ans += solve(s, index + 1,
(sum + i) % z,
0, z);
}
}
}
else {
// If number already becomes
// smaller than S
for (int i = 0; i <= 9; i++)
ans += solve(s, index + 1,
(sum + i) % z, 0,
z);
}
// Return and store the answer
// for the current state
return dp[index][sum][tight] = ans;
}
// Function to clear the states
public static void clear()
{
for (int i[][] : dp) {
for (int j[] : i)
Arrays.fill(j, -1);
}
}
// Driver Code
public static void main(String args[])
{
// Given N, K, and M
int N = 40;
int K = 4;
int M = 2;
// Function Call
System.out.println(search(N, K, M));
}
}
Python3
# Python program for the
# above approach
# Initialize dp array
dp = [[[]]]
# Function to find the
# numbers <= S having
# digits sum divisible
# by M
def solve(s, index,
sum,tight, z):
# Base Case
if (index >= len(s)):
if (sum % z == 0):
return 1
return 0
# Visited state
if (dp[index][sum][tight] != -1):
return dp[index][sum][tight]
# Store answer
ans = 0
# If number still does not
# become smaller than S
if(tight == 1):
# Find limit
l = int(ord(s[index]) -
ord('0'))
# Iterate through all
# the digits
for i in range(0, l + 1):
# If current digit is
# limit
if (i == l):
ans += solve(s, index + 1,
(sum + i) % z,
1, z)
# Number becomes smaller
# than S
else:
ans += solve(s, index + 1,
(sum + i) % z,
0, z)
else:
# If number already becomes
# smaller than S
for i in range(0,10):
ans += solve(s, index + 1,
(sum + i) % z,
0, z)
# Return and store the answer
# for the current state
dp[index][sum][tight] = ans
return ans
# Function to find the Kth number
# > N whose sum of the digits is
# divisible by M
def search(n, k, z):
global dp
dp = [[[-1, -1] for j in range(z)]
for i in range(100001)]
# Initialize lower limit
low = n + 1
# Initialize upper limit
high = 1000000009
# Numbers <= N except 0 with
# digits sum divisible by M
left = solve(str(n), 0,
0, 1, z) - 1
# Initialize answer with -1
ans = -1
while (low <= high):
# Calculate mid
mid = low + (high -
low) // 2
# Mark dp states unvisited
dp = [[[-1, -1] for j in range(z)]
for i in range(100000)]
# Numbers < mid with digits
# sum divisible by M
right = solve(str(mid), 0,
0, 1, z) - 1
# If the current mid is
# satisfy the condition
if (left + k == right):
# Might be the answer
ans = mid
# Update upper limit
high = mid - 1
elif (left + k < right):
# Update upper limit
high = mid - 1
else:
# Update lower limit
low = mid + 1
# Return the answer
return ans
# Driver Code
if __name__ == "__main__":
# Given N, K, and M
N = 40
K = 4
M = 2
# Function Call
print(search(N, K, M))
# This code is contributed by Rutvik_56
C#
// C# program for the above approach
using System;
class GFG{
static int [,,]dp;
// Function to find the Kth number
// > N whose sum of the digits is
// divisible by M
public static int search(int n, int k,
int z)
{
// Initialize dp array
dp = new int[100000 + 1, z, 2];
// Initialize lower limit
int low = n + 1;
// Initialize upper limit
int high = int.MaxValue / 2;
// Mask dp states unvisited
Clear(z);
// Numbers <= N except 0 with
// digits sum divisible by M
int left = solve(n + "", 0,
0, 1, z) - 1;
// Initialize answer with -1
int ans = -1;
while (low <= high)
{
// Calculate mid
int mid = low + (high - low) / 2;
// Mark dp states unvisited
Clear(z);
// Numbers < mid with digits
// sum divisible by M
int right = solve(mid + "", 0,
0, 1, z) - 1;
// If the current mid is
// satisfy the condition
if (left + k == right)
{
// Might be the answer
ans = mid;
// Update upper limit
high = mid - 1;
}
else if (left + k < right)
{
// Update upper limit
high = mid - 1;
}
else
{
// Update lower limit
low = mid + 1;
}
}
// Return the answer
return ans;
}
// Function to find the numbers <= S
// having digits sum divisible by M
public static int solve(String s, int index,
int sum, int tight,
int z)
{
// Base Case
if (index >= s.Length)
{
if (sum % z == 0)
return 1;
return 0;
}
// Visited state
if (dp[index, sum, tight] != -1)
return dp[index, sum, tight];
// Store answer
int ans = 0;
// If number still does not
// become smaller than S
if (tight == 1)
{
// Find limit
int l = s[index] - '0';
// Iterate through all
// the digits
for(int i = 0; i <= l; i++)
{
// If current digit is limit
if (i == l)
{
ans += solve(s, index + 1,
(sum + i) % z,
1, z);
}
// Number becomes smaller than S
else
{
ans += solve(s, index + 1,
(sum + i) % z,
0, z);
}
}
}
else
{
// If number already becomes
// smaller than S
for(int i = 0; i <= 9; i++)
ans += solve(s, index + 1,
(sum + i) % z, 0,
z);
}
// Return and store the answer
// for the current state
return dp[index, sum, tight] = ans;
}
// Function to clear the states
public static void Clear(int z)
{
for(int i = 0; i < 100001; i++)
{
for(int j = 0; j < z; j++)
{
for(int l = 0; l < 2; l++)
dp[i, j, l] = -1;
}
}
}
// Driver Code
public static void Main(String []args)
{
// Given N, K, and M
int N = 40;
int K = 4;
int M = 2;
// Function Call
Console.WriteLine(search(N, K, M));
}
}
// This code is contributed by gauravrajput1
48
时间复杂度: O(log(INT_MAX))
辅助空间: O(K * M * log(INT_MAX))