【LightOJ】1189 - Sum of Factorials(思维)
来源:互联网 发布:省市地区数据库 编辑:程序博客网 时间:2024/04/30 14:40
点击打开题目
Given an integer n, you have to find whether it can be expressed as summation of factorials. For given n, you have to report a solution such that
n = x1! + x2! + ... + xn! (xi < xj for all i < j)
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n ≤ 1018).
Output
For each case, print the case number and the solution in summation of factorial form. If there is no solution then print 'impossible'. There can be multiple solutions, any valid one will do. See the samples for exact formatting.
Sample Input
Output for Sample Input
4
7
7
9
11
Case 1: 1!+3!
Case 2: 0!+3!
Case 3: 1!+2!+3!
Case 4: impossible
没有看到 “大众” 们的代码,不懂他们写的什么意思。
我当时看到了一个规律:后面一个数的阶乘总是大于等于前面的数的阶乘之和。
那么从最后往前走,如果给出的数大于了这个数的阶乘的2倍,那么肯定不成立。如果小于这个数的阶乘,那么继续往前扫,否则就选中这个数,然后减去它的阶乘,一直到这个数减为0.
代码如下:
#include <cstdio>#include <cstring>#include <cmath>#include <queue>#include <vector>#include <stack>#include <algorithm>using namespace std;#define INF 0x3f3f3f3f#define CLR(a,b) memset(a,b,sizeof(a))#define LL long long#define PI acos(-1.0)LL fac[25];bool flag;LL n;stack<int> s;int main(){int u;int Case = 1;fac[0] = 1;LL sum = 1;for (int i = 1 ; i <= 19 ; i++)fac[i] = fac[i-1] * i , sum += fac[i];scanf ("%d",&u);while (u--){scanf ("%lld",&n);printf ("Case %d: ",Case++);if (n > sum){puts("impossible");continue;}while (!s.empty())s.pop();flag = false;for (int i = 19 ; i >= 0 ; i--){if (n < fac[i])continue;else if (n == fac[i]){s.push(i);flag = true;break;}else if (n > 2*fac[i])break;else{s.push(i);n -= fac[i];}}if (flag){while (s.size() != 1){printf ("%d!+",s.top());s.pop();}printf ("%d!\n",s.top());s.pop();}elseputs("impossible");}return 0;}
- 【LightOJ】1189 - Sum of Factorials(思维)
- lightoj-1189-Sum of Factorials【思维】
- LightOJ 1189 - Sum of Factorials
- LightOJ 1189 - Sum of Factorials(贪心)
- LightOJ 1189 - Sum of Factorials(贪心+阶乘)
- 【light-oj】-1189 - Sum of Factorials(思维,数学)
- POJ 1775 FZU 1106 LightOJ 1189 Sum of Factorials
- LOJ 1189 - Sum of Factorials(打表)
- light oj 1189 - Sum of Factorials (阶乘+贪心)
- light oj 1189 - Sum of Factorials (数学)
- poj 1775(Sum of Factorials)
- POJ 1775 Sum of Factorials(数论)
- Sum of Factorials
- Sum of Factorials
- Sum of Factorials
- Sum of Factorials zoj
- poj1775 - Sum of Factorials
- 1038.Sum of Factorials
- Linux系统中“动态库”和“静态库”那点事儿
- Hibernate连接8种常见的数据库配置方式
- druid学习链接
- day4_marquee和背景音乐
- MySQL行级锁、表级锁、页级锁详细介绍
- 【LightOJ】1189 - Sum of Factorials(思维)
- 在Linux中设置允许MySQL用户远程登录,要满足几个条件
- nginx中root和alias的区别
- Qt窗体之间相互传值的三种方式
- 关于二叉排序树的判定
- 0060 如何看懂ping命令的显示结果
- 拼接sql语句 多条入库
- 第二周——程序的多文件组织
- 代理与动态代理模式小结