hdoj 5400 Arithmetic Sequence 【构造等差数列】
2015-09-22 22:31
417 查看
Arithmetic SequenceTime Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1173 Accepted Submission(s): 511 Problem Description A sequence b1,b2,⋯,bn are called (d1,d2)-arithmetic sequence if and only if there exist i(1≤i≤n) such that for every j(1≤j<i),bj+1=bj+d1and for every j(i≤j<n),bj+1=bj+d2. Teacher Mai has a sequence a1,a2,⋯,an. He wants to know how many intervals [l,r](1≤l≤r≤n) there are that al,al+1,⋯,ar are (d1,d2)-arithmetic sequence. Input There are multiple test cases. For each test case, the first line contains three numbers n,d1,d2(1≤n≤105,|d1|,|d2|≤1000), the next line contains n integers a1,a2,⋯,an(|ai|≤109). Output For each test case, print the answer. Sample Input 5 2 -2 0 2 0 -2 0 5 2 3 2 3 3 3 3 Sample Output 12 5 |
满足:存在一个i 使得 b[j+1] = b[j] + d1(1<=j<i) && b[j] = b[j-1] + d2(i<=j<=N).
题意:给你一个N个数组成的序列,问你里面有多少个(d1, d2)序列。
以前看过这道题,没敢写。。。
思路:构造两个等差数列。
定义数组l[i]——为从左到右且以a[i]元素为末尾的等差数列的长度
定义数组r[i]——为从右到左且以a[i]元素为末尾的等差数列的长度
如图:
我们单独考虑把位置3作为i所拥有的区间数目,其中l[3] = 2,r[3] = 2。
一、d1 != d2
区间组合[1, 3] + [3, 4]、[3, 5]中任一个,区间组合[2, 3] + [3, 4]、[3, 5] 共计l[3] * r[3] = 4;
二、d1 != d2 —— 序列1到5是满足题意的等差数列
区间组合[3, 4]和[3, 5]共r[i] = 2个。
(i为2时,算过了[2, 3]。同理统计在位置2为i时,我们只能选择右边的区间,因为i为1时,算过了[1, 2])
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> #define LL long long #define MAXN 100000+10 using namespace std; LL l[MAXN], r[MAXN]; int a[MAXN]; int main() { int N, d1, d2; while(scanf("%d%d%d", &N, &d1, &d2) != EOF) { for(int i = 1; i <= N; i++) scanf("%d", &a[i]); l[1] = 1;//初始只有1 for(int i = 2; i <= N; i++) { if(a[i] == a[i-1] + d1) l[i] = l[i-1] + 1; else l[i] = 1; } r = 1;//初始只有1 for(int i = N-1; i >= 1; i--) { if(a[i] == a[i+1] - d2) r[i] = r[i+1] + 1; else r[i] = 1; } LL ans = 0; if(d1 != d2) { for(int i = 1; i <= N; i++) ans += l[i] * r[i]; } else { for(int i = 1; i <= N; i++) ans += r[i]; } printf("%lld\n", ans); } return 0; }
相关文章推荐
- UITableViewDataSource的代理方法
- UVA 540 Team Queue
- UITableViewDelegate的代理方法
- ZOJ 2587--Unique Attack【判断最小割是否唯一】
- UIColor的使用及拓展
- BindingExpression path using IMultiValueConverter in datacolumn
- JAVA问题总结之24--HashMap键值对(key-value)的操作
- iOS开发之UIActivityIndicatorView(二)
- UIButton的响应事件 UIControlEvents 类型说明
- Unix环境编程学习笔记-------通读APUE第一遍后的疑问???????
- systemUI之statusbar
- IOS学习之 UITabBar
- UIday2201:IOS开发中的多线程
- 判断修改的中的值,用前面的,否则容易获得空值;this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue; VS bool b = (bool)this.dataGridView1.Rows[i].Cells[0].Value;
- iOS开发之UIalertView
- UI一揽子计划 22 (多线程概述、NSThread、NSOperationQueue 、GCD、多线程管理)
- UI一揽子计划 21 (UICollectionView、SDWebImage第三方类库加载图片的使用、集合视图的布局UICollectionViewFlowLayout 、自定义Cell、布局协议
- iOS9新特性-UIStackView(简单介绍)
- iOS开发 ----- UISearchBar_UISearchController
- iOS开发 ----- UICollectionView