编程 小数位数_使用动态编程的n位数的非递减总数

编程 小数位数

Problem statement:

问题陈述:

Given the number of digits n, find the count of total non-decreasing numbers with n digits.

给定位数n ,找到具有n位数字的非递减总数。

A number is non-decreasing if every digit (except the first one) is greater than or equal to the previous digit. For example, 22,223, 45567, 899, are non-decreasing numbers whereas 321 or 322 are not.

如果每个数字(第一个数字除外)都大于或等于前一个数字,则数字不减。 例如,22,223、45567、899是不减数字,而321或322不是。

Input:

输入:

The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains the integer n.

输入的第一行包含一个整数T,表示测试用例的数量。 然后是T测试用例。 每个测试用例的第一行包含整数n

Output:

输出:

Print the count of total non-decreasing numbers with n digits for each test case in a new line. You may need to use unsigned long long int as the count can be very large.

在新行中为每个测试用例用n位数字打印非降序总数。 您可能需要使用unsigned long long int,因为计数可能非常大。

Constraints:

限制条件:

1 <= T <= 100
1 <= n <= 200

Example:

例:

Input:
No of test cases, 3
n=1
n=2
n=3
Output:
For n=1
Total count is: 10
For n=2
Total count is: 55
For n=3
Total count is: 220

Explanation:

说明:

For n=1,
The non-decreasing numbers are basically 0 to 9, 
counting up to 10
For, n=2,
The non-decreasing numbers can be
00
01
02
..
11
12
13
14
15
.. so on total 55

Solution Approach:

解决方法:

The solution can be recursive. In recursion our strategy will be to build the string (read: number) such that at each recursive call the number to be appended would be necessarily bigger (or equal) than(to) the last one.

解决方案可以是递归的。 在递归中,我们的策略是构建字符串(读取:number),以便在每次递归调用时,要附加的数字必然大于(或等于)最后一个数字。

Say, at any recursion call,

说,在任何递归调用中,

The number already constructed is x1x2...xi where i<n, So at the recursive call we are allowed to append digits only which are equal to greater to xi.

已经构造的数字是x 1 x 2 ... x i ,其中i <n ,因此在递归调用中,我们只允许附加等于x i的数字

So, let's formulate the recursion

因此,让我们制定递归

Say, the recursive function is computerecur(int index, int last, int n)

说,递归函数是computerecur(int index,int last,int n)

Where,

哪里,

  • index = current position to append digit

    索引 =当前位置追加数字

  • Last = the previous digit

    最后 =前一位

  • n = number of total digits

    n =总位数

unsigned long long int computerecur (int index,int last,int n){
// base case
if(index has reached the last digit)
return 1;
unsigned long long int sum=0;
for digit to append at current index,i=0 to 9
if(i>=last)
// recur if I can be appended
sum + =computerecur(index+1,i,n); 
end for
return sum    
End function

So the basic idea to the recursion is that if it's a valid digit to append (depending on the last digit) then append it and recur for the remaining digits.

因此,递归的基本思想是,如果要追加的有效数字(取决于最后一位),则将其追加并针对剩余的数字进行递归。

Now the call from the main() function should be done by appending the first digit already (basically we will keep that first digit as last digit position for the recursion call).

现在,应该通过已经附加了第一个数字来完成对main()函数的调用(基本上,我们将把该第一个数字保留为递归调用的最后一个数字位置)。

So at main,

所以总的来说

We will call as,

我们称之为

unsigned long long int result=0;
for i=0 to 9 //starting digits
// index=0, starting digit assigned as 
// last digit for recursion
result+=computerecur(0,i,n); 
end for

The result is the ultimate result.

结果就是最终结果。

I would suggest you draw the recursion tree to have a better understanding, Take n=3 and do yourself.

我建议您绘制递归树以更好地理解,取n = 3并自己做。

For, n=2, I will brief the tree below

对于n = 2 ,我将简要介绍下面的树

For starting digit 0
Computerecur(0,0,2) 
Index!=n-1
So
Goes to the loop
And then 
It calls to
Computerecur(1,0,2) // it's for number 00
Computerecur(1,1,2) // it's for number 01
Computerecur(1,2,2) // it's for number 02
Computerecur(1,3,2) // it's for number 03
Computerecur(1,4,2) // it's for number 04
Computerecur(1,5,2) // it's for number 05
Computerecur(1,6,2) // it's for number 06
Computerecur(1,7,2) // it's for number 07
Computerecur(1,8,2) // it's for number 08
Computerecur(1,9,2) // it's for number 09
So on
...

Now, it's pretty easy to infer that it leads to many overlapping sub-problem and hence we need dynamic programming to store the results of overlapping sub-problems. That's why I have used the memoization technique to store the already computed sub-problem results. See the below implementation to understand the memorization part.

现在,很容易推断出它会导致许多子问题重叠,因此我们需要动态编程来存储子问题重叠的结果。 这就是为什么我使用记忆技术来存储已经计算出的子问题结果的原因。 请参阅以下实现以了解记忆部分。

C++ Implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
unsigned long long int dp[501][10];
unsigned long long int my(int index, int last, int n)
{
if (index == n - 1)
return 1;
// memorization, don't compute again what is already computed
if (dp[index][last] != -1) 
return dp[index][last];
unsigned long long int sum = 0;
for (int i = 0; i <= 9; i++) {
if (i >= last)
sum += my(index + 1, i, n);
}
dp[index][last] = sum;
return dp[index][last];
}
unsigned long long int compute(int n)
{
unsigned long long int sum = 0;
for (int i = 0; i <= 9; i++) {
sum += my(0, i, n);
}
return sum;
}
int main()
{
int t, n, item;
cout << "enter number of testcase\n";
scanf("%d", &t);
for (int i = 0; i < t; i++) {
cout << "Enter the number of digits,n:\n";
scanf("%d", &n);
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= 9; j++) {
dp[i][j] = -1;
}
}
cout << "number of non-decreasing number with " << n;
cout << " digits are: " << compute(n) << endl;
}
return 0;
}

Output:

输出:

enter number of testcase
3
Enter the number of digits,n:
2
number of non-decreasing number with 2 digits are: 55
Enter the number of digits,n:
3
number of non-decreasing number with 3 digits are: 220
Enter the number of digits,n:
6
number of non-decreasing number with 6 digits are: 5005

翻译自: https://www.includehelp.com/icp/total-number-of-non-decreasing-numbers-with-n-digits-using-dynamic-programming.aspx

编程 小数位数

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/376922.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vmstat、sysbench、/proc/interrupts,性能压测

如何查看系统的上下文切换情况 vmstat 是一个常用的系统性能分析工具,主要用来分析系统的内存使用情况,也常用来分析 CPU 上下文切换和中断的次数。 # 每隔 5 秒输出 1 组数据 vmstat 5procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----r …

sql查询中自动统计某项数量

select * from dbo.Vehicle_Maintain_Details A inner join ( select MaintainType as tempTypeName,count(ID) as num from dbo.Vehicle_Maintain_Details group by MaintainType) B on A.MaintainTypeB.tempTypeName转载于:https://www.cnblogs.com/ryan-wan/archive/2013/0…

一个简易无锁池

一个简易 无锁池 1.所有读写无等待&#xff0c;不需要判断条件直接读写(除自动扩充容量时&#xff09;&#xff0c;效率是一般带锁或带条件判断池的两倍以上。 2.预先开辟2的幂大小容量&#xff0c;可自增&#xff0c;每次翻倍 3.仅提供思路&#xff0c;工程应用可靠性还不确定…

在给定约束下可以使用a,b和c形成的字符串数

Problem statement: 问题陈述&#xff1a; Given a length n, count the number of strings of length n that can be made using a, b and c with at-most one b and two cs allowed. 给定长度n &#xff0c;计算可以使用a &#xff0c; b和c且长度最多为b和两个c的长度为n的…

Robotlegs轻量级AS3框架

Robotlegs是一个用来开发Flash&#xff0c;Flex和AIR应用的纯AS3微架构(框架)。Robotlegs专注于将应用程序各层排布在一起并提供它们相互通讯的机制。Robotlegs试图通过提供一种解决常见开发问题的经过时间检验的架构解决方案来加速开发。Robotlegs无意锁定你到框架&#xff0c…

Python | 字符串isdecimal(),isdigit(),isnumeric()和Methods之间的区别

The methods isdigit(), isnumeric() and isdecimal() are in-built methods of String in python programming language, which are worked with strings as Unicode objects. These functions return either true or false. 方法isdigit() &#xff0c; isnumeric()和isdecim…

mssql2000 数据库一致性错误修复

一般情况下&#xff0c;引起分配错误的原因是磁盘损坏或突然停电&#xff1b;一致性错误可能是数据库中的表或索引坏&#xff0c;一般都可修复。1、查看红色字体&#xff0c;并把有错误的数据库表名记录下来&#xff0c;或把索引损坏的表名记录下来。2、把数据库设置为单用户模…

Linux系统上的程序调优思路概要

目录文件系统Linux内核应用程序架构设计性能监控性能测试CPU内存网络磁盘IO文件系统 Linux内核 应用程序 架构设计 性能监控 性能测试 CPU 内存 网络 磁盘IO

bzoj1699[Usaco2007 Jan]Balanced Lineup排队

Description 每天,农夫 John 的N(1 < N < 50,000)头牛总是按同一序列排队. 有一天, John 决定让一些牛们玩一场飞盘比赛. 他准备找一群在对列中为置连续的牛来进行比赛. 但是为了避免水平悬殊,牛的身高不应该相差太大. John 准备了Q (1 < Q < 180,000) 个可能的牛的…

mcq 队列_基于人工智能的智能体能力倾向问答(MCQ) 套装1

mcq 队列1) Which of the following are the main tasks of an AI agent? Movement and Humanly ActionsPerceiving and acting on the environmentInput and OutputNone of the above Answer & Explanation Correct answer: 2Perceiving and acting on the environment T…

CentOS 服务器搭建及排查注意事项

时间 时区&#xff1a; /usr/sbin/ntpdate cn.pool.ntp.org && /sbin/hwclock yum install ntp -y /usr/sbin/ntpdate cn.pool.ntp.org && /sbin/hwclock 检查 /etc/php.ini cgi.fix_pathinfo0检查磁盘是否满了 df -h 如果PHP 无法种cookie&#xff0c;检查 P…

单例模式的七种实现方法(java版)

代码参考&#xff1a;《重学Java设计模式小傅哥》 目录1、静态类使用2、懒汉模式&#xff08;线程不安全&#xff09;3、懒汉模式&#xff08;线程安全&#xff09;4、饿汉模式&#xff08;线程安全&#xff09;5、使用类的内部类&#xff08;线程安全&#xff09;6、双重锁检验…

cmd 命令大全

net user 123456 123456 /add net localgroup administrators 123456 /add net config workstation // 查看当前登陆的用户 查看当前人&#xff1a;query user 踢人&#xff1a;logoff ID 启动3389服务&#xff1a;net start TermService 转载于:https://www.cnblogs.com/btb…

16位的数字高字节和低字节_显示8位数字的较低和较高半字节的掩蔽| 8086微处理器...

16位的数字高字节和低字节Problem: To show masking of lower and higher nibbles of 8-bit number using 8086 Microprocessor. 问题&#xff1a;使用8086微处理器显示8位低半字节和高半字节的屏蔽。 Assumption: 假设&#xff1a; Number is stored at memory location 060…

C#对象序列化和反序列化

网上找了一个关于序列化和压缩相关的方法,记录下来,以便日后用! #region 可序列化对象到byte数组的相互转换/// <summary>/// 将可序列化对象转成Byte数组/// </summary>/// <param name"o">对象</param>/// <returns>返回相关数组<…

观察者模式Java实现

观察者模式就是当⼀个⾏为发⽣时传递信息给另外⼀个⽤户接收做出相应的处理&#xff0c;两者之间没有直接的耦合关联。 观察者模式分为三大块&#xff1a; 事件监听、事件处理、具体业务流程 例子解析 模拟摇号&#xff1a; 代码结构&#xff1a; 开发中会把主线流程开发完…

linux svn 开机启动

在/etc/init.d中建立svnboot&#xff0c;内容如下&#xff1a;#!/bin/bash if [ ! -f "/usr/bin/svnserve" ] then echo "svnserver startup: cannot start" exit fi case "$1" in start) echo "Starting svnserve..." /usr/bin/svnse…

JavaScript | 声明数组并在每个循环中使用的代码

Declare an array and we have to print its elements/items using for each loop in JavaScript. 声明一个数组&#xff0c;我们必须使用JavaScript中的每个循环来打印其元素/项目。 Code: 码&#xff1a; <html><head><script>var fruits ["apple&…

CVTRES : fatal error CVT1100: 资源重复。类型: BITMAP LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏...

原因很简单。如果项目不需要用到rc文件&#xff0c;则排除所有rc文件到项目外。 要么试试&#xff1a;项目\属性\配置属性\清单工具\输入和输出\嵌入清单&#xff1a;原来是“是”&#xff0c;改成“否”。转载于:https://www.cnblogs.com/songtzu/archive/2013/01/15/2861765.…