hdoj 5212 Code 【数学+思维】
来源:互联网 发布:phonewindow源码 编辑:程序博客网 时间:2024/05/10 13:13
题目链接:hdoj 5212 Code
Code
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 677 Accepted Submission(s): 262
Problem Description
WLD likes playing with codes.One day he is writing a function.Howerver,his computer breaks down because the function is too powerful.He is very sad.Can you help him?
The function:
int calc
{
int res=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){ res+=gcd(a[i],a[j])*(gcd(a[i],a[j])-1); res%=10007;}
return res;
}
Input
There are Multiple Cases.(At MOST 10)
For each case:
The first line contains an integer N(1≤N≤10000).
The next line contains N integers a1,a2,…,aN(1≤ai≤10000).
Output
For each case:
Print an integer,denoting what the function returns.
Sample Input
5
1 3 4 2 4
Sample Output
64
Hint
gcd(x,y) means the greatest common divisor of x and y.
题意:优化程序,快速求解。
思路:我们考虑以d为gcd的数对做出的贡献。
记a[]中d的倍数有cnt[d]个,在d的倍数中,会有若干个数组成数对的gcd为2*d,3*d……。我们设置ans[d]为以d为gcd的数对个数,那么有ans[d] = total - ans[2*d] - ans[3*d] - … 。其中total为cnt[d]*cnt[d]。
发现求解d,需要2*d、3*d……,而求解2*d需要3*d,4*d……。那么我们直接倒着来求就好了。时间复杂度O(nlogn)。
AC代码:
#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <queue>#include <cmath>#define fi first#define se second#define ll o<<1#define rr o<<1|1#define CLR(a, b) memset(a, (b), sizeof(a))using namespace std;typedef long long LL;typedef pair<int, int> pii;const int MOD = 1e4 + 7;const int MAXN = 1e4 + 10;void add(LL &x, LL y) { x += y; x %= MOD; }LL cnt[MAXN], ans[MAXN];int main(){ int n; while(scanf("%d", &n) != EOF) { int Max = 0; CLR(cnt, 0); for(int i = 1; i <= n; i++) { int v; scanf("%d", &v); Max = max(Max, v); for(int j = 1; j <= sqrt(v); j++) { if(v % j == 0) { cnt[j]++; if(j * j != v) { cnt[v/j]++; } } } } CLR(ans, 0); LL sum = 0; for(int i = Max; i >= 1; i--) { ans[i] = cnt[i] * cnt[i]; for(int j = i * 2; j <= Max; j += i) { ans[i] -= ans[j]; } add(sum, ans[i] * (i-1) % MOD * i % MOD); } printf("%lld\n", sum); } return 0;}
- hdoj 5212 Code 【数学+思维】
- hdoj 4944 FSF’s game 【数学思维】
- hdoj 4810 Wall Painting 【思维 + 组合数学】
- HDOJ-----1997汉诺塔VII-----数学思维题
- hdoj 5620 KK's Steel (数学思维,那波婓切)
- hdu 5212 Code【容斥原理】【思维】
- hdoj 5734 5742 5744 2016多校2(复现)<数学---思维----贪心>
- hdoj Code 5212 (容斥原理)
- hdoj 5100 Chessboard 【思维】
- hdoj 5587 Array 【思维】
- hdoj 5200 Trees 【思维】
- hdoj 5480 Conturbatio 【思维】
- hdoj 5671 Matrix 【思维】
- hdoj 5480 Conturbatio (思维)
- 矩阵的数学思维
- 数学的思维
- 数学思维的培养
- HDU4357(数学思维题)
- Andriod基础:RatingBar设置
- 稀疏表示
- Eclipse如何快速调试系统App(具有系统权限的Android App)即Eclipse导入系统签名快速调试系统App
- 二叉树的生成与遍历
- webview
- hdoj 5212 Code 【数学+思维】
- c++第三次实验
- Cmaker 是什么
- eclipse使用git解决冲突
- Lucene 查询中的距离查询(proximity query)
- HashMap内部实现及源码分析
- mysql查询和索引优化
- (二)PendingIntent
- OpenCL Bug: Unrecognized Token during Kernel Compilation