题目:我们在研究罗马数字。罗马数字只有4个字符,I,V,X,L分别代表1,5,10,100。一个罗马数字的值为该数字包含的字符代表数字的和,而与字符的顺序无关。例如XXXV=35,IXI=12.
现在求问一个长度为 nn 的罗马数字可以有多少种不同的值。( n \leq 10^9n≤109 )
最坑爹的一道题目。
首先我们可知,在 \{1,5,10,50 \}{1,5,10,50} 中取 nn 个组成不同数的方案数,和在 \{0,4,9,49 \}{0,4,9,49} 中取 nn 个的方案数是一样的。这样转化了之后,这些数两两之间互质,并且出现了0,更加好处理。
我们现在尽量去限制4和9,使得0和49可以任意取。
然后我们发现,9个4=4个9+5个0,为了避免重复,我们取的4的个数不能超过8个。
打表找用0和49代替4和9的例子,发现1个4+5个9=1个49+5个0,所以只要取了4,取9的个数就不能超过4个。如果没有取4,那么取9的个数就不能超过48个。
接下来发现,2个4+1个49+6个0=9个9。也就是说,当不取4的时候,取9的个数不能超过8个。
有了以上三点限制之后,我们可以枚举取4和取9的个数 ii 和 jj ,剩下的数全选0和49,方案数是 n-i-jn−i−j
见下面这个代码,可以发现,当循环跑满了之后的答案会呈现一种线性增长,这就是打表找出的规律的由来。
先打表找规律,再写代码。
第一种打表代码:
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<map>
using namespace std;
map<long long,int> mapp;
long long dfs(int n)
{
mapp.clear();
long long sum=0;
for (int i=0; i<=n; i++)
{
for (int j=0; i+j<=n; j++)
{
for (int k=0; i+j+k<=n; k++)
{
int l=n-i-j-k;
long long tmp=i+j*5+k*10+l*50;
if (mapp.count(tmp)==0)
{
mapp[tmp]=1;
sum++;
}
}
}
}
return sum;
}
int main()
{
long long t;
scanf("%lld",&t);
if (t<=20) printf("%lld\n",dfs(t));
else printf("%lld\n",dfs(20)+49*(t-20));
return 0;
}
第二种打表代码:
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <iostream>
#include <assert.h>
#include <fstream>
using namespace std;
int ans=0,sum=0,n;
set<int> s;
int m[5]={0,1,5,10,50};
void dfs(int t){
if(t==n+1){
if(s.find(sum)!=s.end())
return;
ans++;
s.insert(sum);
return;
}
for(int i=1;i<=4;i++){
sum+=m[i];
dfs(t+1);
sum-=m[i];
}
}
int main(){
for(int i=1;i<=60;i++){
n=i;
dfs(1);
cout<<ans<<",";
ans=0;
sum=0;
s.clear();
}
}
ac代码:
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <iostream>
#include <assert.h>
#include <fstream>
using namespace std;
int main(){
long long n;
cin>>n;
int m[30]={0,4,10,20,35,56,83,116,155,198,244,292,341,390,439};
cout<<(n<=11?m[n]:(long long)(n-11)*49+292);