ACM程序设计选修课——1051: Glamor Sequence(YY+求和公式)
2016-03-25 19:35
357 查看
1051: Glamor Sequence
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 16 Solved: 5
[Submit][Status][Web
Board]
Description
you have a sequence +1, +2, +3, ... +m, -(m + 1), -(m + 2), ..., -(2m), (2m + 1), (2m + 2), ..., (3m), .....and you need calculator sum of the first n items.
Input
For each test case, there is a line contains two integers n and m, (1 <= m <= n <= 1000000000).Output
For each test case, print sum of the first n items.Sample Input
8 2 10 3
Sample Output
-8 5
HINT
For the first sample, the sequence is 1, 2, -3, -4, 5, 6, -7, -8, so the answer is -8.For the second sample, the sequence is 1, 2, 3, -4, -5, -6, 7, 8, 9, -10, so the answer is 5.
想了很久还是不会。问了同学大概思路,确是用等差数列求和公式,但是先前的做法效率比较低,用了for循环,一旦出现n比较大而m非常小的话就会超时,比如n=1000000000,m=1,test测试一下5秒多。
因此一种思路是这样:
可以发现从1开始前2*m项的和的绝对值是一个常数即m,e=n-n%(2*m)那么只需处理后面e+1~n的数字即可。因此可以有如下规律
设剩下的区间为e+1~n(也可能是e+m)。
1、若e+m<=n——即数轴分布情况为e+1~e+m~n。只需将之前的所有完整段的和加上Sum[e+1,e+m]即可,且每一项都是正数。
2、若e+m>n——即数轴分布情况为e+1~n~e+m。那么要计算S1[e+1,n]与S2[n+1,e+m],ans=ans+S1-S2。
#include<iostream> #include<string> #include<algorithm> using namespace std; int main(void) { long long n,m,e; long long ans; while (~scanf("%lld%lld",&n,&m)) { e=n-n%(2*m); ans=(e)*(-m)/2;//所有完整段求和 if(e+m<n)//分类讨论 { ans=ans+(2*e+1+m)*m/2; ans=ans-(e+m+1+n)*(n-e-m)/2; } else if(e+m>n) { ans=ans+(e+1+n)*(n-e)/2; } else { ans=ans+(2*e+1+m)*m/2; } printf("%lld\n",ans);//这题要用long long来储存答案 } return 0; }
相关文章推荐
- leetcode——225—— Implement Stack using Queues
- POJ 2299 Ultra-QuickSort(逆序对数,线段树/树状数组/归并排序)
- requests模拟ajax异步请求
- Hbuilder 常用快捷键汇总
- 多线程——NSOperationQueue
- mui关于页面间传值的方法
- 关于如何修改UISearchBa灰色背景
- Android官方开发文档Training系列课程中文版:使用Fragment构建动态UI之Fragment创建
- Requirements 101: User Stories vs. Use Cases
- Handler原理笔记
- ggplot2快速教程Quick Introduction to ggplot2
- poj 2081 Recaman's Sequence
- Web 快速开发框架 WebBuilder 7 发布
- multidex导入至build失败问题
- lintcode: Implement Queue by Two Stacks
- uint8、double、mat2uint、imhist绘直方图w恩替藐视
- JAVA顺序表(Sequential List)操作
- Android4.42-Setting源码分析之蓝牙模块Bluetooth(下)
- 使用SOAPUI测试WEBAPI接口
- web UI技术方案备忘