华中农业大学第四届程序设计大赛网络同步赛-1020: Arithmetic Sequence,题挺好的,考思路;
2016-05-16 16:00
435 查看
1020: Arithmetic Sequence
Time Limit: 1 Sec Memory Limit: 128MB
Submit: 1834 Solved: 322
->打开链接<-
Description
Giving a number sequence A withlength n, you should choosing m numbers from A(ignore
the order) which can form an arithmetic sequence and make m as large as possible.
Input
There are multiple test cases. In each test case, the first line contains a positiveinteger n. The second line contains n integers
separated by spaces, indicating the number sequence A. All the integers are positive and not more than 2000. The input will end by EOF.
Output
For each test case, output the maximum asthe answer in one line.
Sample Input
5 1 3 5 7 10 8 4 2 7 11 3 1 9 5
Sample Output
4 6
HINT
In the first test case, you should choose 1,3,5,7 to form the arithmetic sequence andits length is 4.
In the second test case, you should choose 1,3,5,7,9,11 and the length is 6.
题意:求一个等差数列,使得长度最长;
思路:先排序a[i],用二维数组b[ ][ ]一维储存公差d,另一维储存这个值(b[
d ][ a[i]+d]),如果这个值存在则二维数组的值加一(b[ d ][ a[i]+d] =b[ d ][ a[i] ]+1),并与当前最大值比较,下次再用当前的(a[i]+d)加上相同的公差d判断得到的值(a[i]+2d)是否存在,如果存在,则b[
d ][ a[i]+2d ] =b[ d ][ a[i] +d ]+1;继续与当前最大长度比较;这样就用的两层for循环,巧妙地避开了超时的问题;如果有疑问请看代码:
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int N=2000+10; int a ,b ,v ; int main() { int n,i,j; while(~scanf("%d",&n)) { memset(v,0,sizeof(v)); memset(b,0,sizeof(b)); for(i=1; i<=n; i++) { scanf("%d",&a[i]); v[a[i]]=1;//用来判断a[i]+d是否存在; } if(n<=2) printf("%d\n",n); else { sort(a+1,a+1+n); int m1=1,m=0,k=a -a[1];//用m储存最大长度;并求出公差最大值; for(i=2; i<=n; i++)//公差为0的情况; { if(a[i]==a[i-1]) m1++; else m1=1; m=max(m,m1); } for(i=1; i<=n; i++)//两层循环; { for(j=1; j<=k; j++)//公差的所有可能值,注意公差为0已经在上面判断过了; { if(a[i]+j>a ) break; if(v[a[i]+j])//如果存在; { if(!b[j][a[i]]) b[j][a[i]]=1;表示以a[i]为首项, 公差为d,所以值要赋为1; b[j][a[i]+j]=b[j][a[i]]+1;//关键,这样就是层层更新递推; } m=max(b[j][a[i]+j],m); // printf("%d %d %d\n",i,j,b[j][a[i]+j]); } } printf("%d\n",m); } } return 0; }思路确实很好,不过应该有更好的方法思路;恭请指教
相关文章推荐
- HTTPS 协议 认识与加深
- java网络编程基础
- 网络优化步骤
- 游戏中的网络同步机制——Lockstep
- 通过Loadrunner 录制ISO设备的HTTP请求
- http中get和post请求差别
- Http请求头信息相关
- 基于TCP(面向连接)的socket编程
- iOS应用开发中AFNetworking库的常用HTTP操作方法小结
- 网络层概念学习之一(基本概念、路由器、选路算法)
- part1:7-Linux网络配置
- Recording HTTP traffic on iOS devices with HP LoadRunner
- HttpUrlConnection的post方式用法
- 图解HTTPS
- tcpdump抓包
- 在ASP.NET MVC中使用Log4Net进行多种HttpCode日志的记录
- VMware虚拟机-无法连接网络
- SDN的一些初级入门介绍
- VMware Workstation学习之路——网络设置——NAT连接方式
- 《图解HTTP》读书笔记