JZOJ 3509. 【NOIP2013模拟11.5B组】倒霉的小C

Description

小G最近迷上了岛国动漫《Angel Beats》,她为了画出一个更霸气的Angel Beats的logo,想了如下办法:

从(0,0)开始,画到(n,1),再从(n,1),画到(2*n,-1),再到(3*n,2),再到(4*n,-2),依此类推,即每次画出一个(n,(-1)^(i+1)*i)的向量,一共画出n个这样的向量。现在小G想让小C求出这个图形穿过了多少格点(坐标都是整数)。

由于小C想要认真地听他的数学课并且想自己在接力赛中因RP暴光而发生接力棒传错这类的糗事,所以这个问题就交给你啦。小G说,如果连你也解决不好,就把你的RP也吸光。
 

Input

输入文件中仅一行为一个整数n。

Output

输出文件中仅一行为一个数,表示穿过的格点数。
 

Sample Input

4

Sample Output

9
 
做法:

通过简单观察可以发现,每次画出向量(n,i)经过的格点个数为gcd(i,n),那么答案就等于Ans=1+

 

直接求解的时间复杂度是O(n)的。

那么Ans=1+

其中d为n的约数。fai(n)表示1~n中与n互质的数的个数。通过这样的变形,我们就可以得到时间复杂度为O(C*sqrt(n))的算法,C为n的约数个数。

代码如下:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <string>
 4 #include <cstring>
 5 #include <cmath>
 6 #define LL long long
 7 using namespace std;
 8 LL n, ans, k;
 9 
10 LL phi(LL x)
11 {
12     LL k = x;
13     for (int i = 2; x > 1; i++)
14         if (x % i == 0)
15         {
16             k -= k / i;
17             while (x % i == 0)    x /= i;    
18         }
19     return k;
20 }
21 
22 int main()
23 {
24     freopen("beats.in", "r", stdin);
25     freopen("beats.out", "w", stdout);
26     cin >> n;
27     int p = sqrt(n);
28     for (int i = 1; i <= p; i++)
29         if (n % i == 0)
30         {
31             k = i;
32             ans += k * phi(n / k);
33             if (k != n / k)    k = n / i, ans += k * phi(n / k);
34         }
35     cout << ans + 1;
36     return 0;
37 }
View Code

猜你喜欢

转载自www.cnblogs.com/traveller-ly/p/9338603.html