题目链接:http://codeforces.com/problemset/problem/339/B

题目理解不难,这句是解题的关键 In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i 。从样例1的提示,可以知道,如果a[i] > a[i+1],则需要继续顺时针走下去,直到到达n,接着重新从1开始数,直到a[i+1]。

这里要注意的是题目中  2 ≤ n ≤ 105, 1 ≤ m ≤ 105   ,  暗示了我们数据是比较大的,为什么呢?如果输入的序列是递减的,那么每一次转换到下一个数都要经过一次循环,最坏情况是10^5 * 10^5,即10^10 = 10 000 000 000,所以需要要用到64位整数[-2^63, 2^63),即即-9223372036854775808~9223372036854775807。常规的32位整数只能够处理40亿以下的数。

 #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std; const int maxn = + ;
typedef long long LL; // 关键 int main()
{
int i, j, m, n;
LL a[maxn];
LL cnt, cnt1; // cnt用来统计时间的总和,cnt1用来统计已经完成的任务
while (cin >> n >> m)
{
for (i = ; i < m; i++)
{
scanf("%I64d", &a[i]);
}
for (cnt = -, cnt1 = i = , j = ; i < m; i++)
{
while (a[i] >= j)
{
j++;
cnt++;
}
cnt1++;
if (a[i+] < a[i] && i+ < m)
{
j--; // 退出while过程中,j加多了一次,需要减回来再统计
while (j != n)
{
j++; // 必须要达到n之后才能继续从1开始数到a[i+1]
cnt++;
}
j = ; // j到达n之后要继续开始新一轮的顺时针计数(从1开始)
}
if (cnt1 == m) // 所有任务已经完成则退出
break;
}
printf("%I64d\n", cnt);
}
return ;
}

优化后的代码(以时间换空间的,上面那个是30ms,800kB,GNU C++提交,下面的是156ms,0kB,MS C++提交)

 #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std; int main()
{
_int64 cnt;
int t1, t2, i, k, m, n;
while (cin >> n >> m)
{
t2 = ;
k = ;
for (cnt = i = ; i < m; i++)
{
cin >> t1;
if (t1 < t2)
k = n;
cnt += k + t1 - t2;
k = ;
t2 = t1;
}
printf("%I64d\n", cnt);
}
return ;
}

最新文章

  1. Spring 配置解析之Properties
  2. 练习sql语句的好去处——http://www.sqlzoo.cn/
  3. mysql行转列、列转行示例
  4. POJ1236Network of Schools(强连通分量 + 缩点)
  5. 【bzoj3624】【apio2008】免费道路
  6. Android生成一维码
  7. linux(CentOS)-nodejs项目部署
  8. 暂停更新Blog
  9. 集群——LVS理论(转)
  10. 【hihocoder 1257 Snake Carpet】构造
  11. OC 调用JS 代码 处理HTML5 实战
  12. 使用Gradle构建Android项目
  13. Error Code: 1175. You are using safe update mode and you tried to update a table
  14. JMeter学习笔记02-基础介绍
  15. 格式化代码引发的css编译失败
  16. Ping 命令实战小结--TCP/IP协议学习
  17. 【1天】黑马程序员27天视频学习笔记【Day02】
  18. CentOS7.0小随笔——指令基本操作(Part.A)
  19. 一起学习造轮子(二):从零开始写一个Redux
  20. java框架之Spring(3)-JDBC模板使用&amp;事务管理

热门文章

  1. RHCS配置web高可用集群
  2. 【Beta阶段】发布说明
  3. std::function,std::bind
  4. SCI完全攻略:从构思到发表
  5. Lua函数之二
  6. Jquery 鼠标事件解析
  7. [转]优化wp_head()
  8. Entity Framework 自动生成CodeFirst代码
  9. Linux瑞士军刀:密码管理Keeweb
  10. NGUI 学习笔记实战——制作商城UI界面