📜  超过 N 的第 K 个数字,其数字之和可被 M 整除

📅  最后修改于: 2021-09-17 06:45:09             🧑  作者: Mango

给定整数NKM ,任务是找到大于NK数字,其数字之和可被M整除。

例子:

朴素的方法:最简单的方法是检查每个大于N的数字,如果其数字之和可被M整除,则将计数器增加1 。继续检查数字,直到计数器等于K

时间复杂度: O(K)
辅助空间: O(1)

高效的方法:这个想法是使用 动态规划 和二分搜索。请按照以下步骤解决问题:

  • 首先,创建一个递归记忆函数,找出小于或等于S且能被M整除的整数的总数,如下所示:
  • 现在使用二分搜索,下限是N+1 ,上限是一些大整数。
  • 初始化一个变量left用于存储小于或等于N的数字总和可被M整除的总数。
  • 找到下限和上限的中点,然后使用上面的dp函数找到小于或等于中点的数字之和可以被M整除的数字。让它是对的
  • 如果left + K等于right然后将答案更新为 mid 并将上限设置为中点 – 1
  • 否则,如果left + K小于 right,则将上限设置为midpoint-1
  • 如果left + K大于 right,则将下限设置为midpoint+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


Javascript


输出
48

时间复杂度: O(log(INT_MAX))
辅助空间: O(K * M * log(INT_MAX))

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程