codeforces B. Xenia and Ringroad 解题报告

题目链接: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亿以下的数。

   

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 using namespace std;
 5 
 6 const int maxn = 100000 + 5;
 7 typedef long long LL;    // 关键
 8 
 9 int main()
10 {
11     int i, j, m, n;
12     LL a[maxn];
13     LL cnt, cnt1;    // cnt用来统计时间的总和,cnt1用来统计已经完成的任务
14     while (cin >> n >> m)
15     {
16         for (i = 0; i < m; i++)
17         {
18             scanf("%I64d", &a[i]);
19         }
20         for (cnt = -1, cnt1 = i = 0, j = 1; i < m; i++)
21         {
22             while (a[i] >= j)
23             {
24                 j++;
25                 cnt++;
26             }
27             cnt1++;
28             if (a[i+1] < a[i] && i+1 < m)
29             {
30                 j--;   // 退出while过程中,j加多了一次,需要减回来再统计
31                 while (j != n)
32                 {
33                     j++;    // 必须要达到n之后才能继续从1开始数到a[i+1]
34                     cnt++;
35                 }
36                 j = 1;   // j到达n之后要继续开始新一轮的顺时针计数(从1开始)
37             }
38             if (cnt1 == m)   // 所有任务已经完成则退出
39                 break;
40         }
41         printf("%I64d\n", cnt);
42     }
43     return 0;
44 }

    

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

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     _int64 cnt;
 9     int t1, t2, i, k,  m, n;
10     while (cin >> n >> m)
11     {
12         t2 = 1;
13         k = 0;
14         for (cnt = i = 0; i < m; i++)
15         {
16             cin >> t1;
17             if (t1 < t2)    
18                 k = n;    
19             cnt += k + t1 - t2;
20             k = 0;
21             t2 = t1;
22         }
23         printf("%I64d\n", cnt);
24     }
25     return 0;
26 }
原文地址:https://www.cnblogs.com/windysai/p/3287085.html