首页 > 代码库 > 数论——HDU 4961

数论——HDU 4961

对应HDU题目:点击打开链接


Boring Sum
Time Limit: 1000MS Memory Limit: 131072KB 64bit IO Format: %I64d & %I64u

[Submit]   [Go Back]   [Status]  

Description

Number theory is interesting, while this problem is boring. 

Here is the problem. Given an integer sequence a 1, a 2, …, a n, let S(i) = {j|1<=j<i, and a j is a multiple of a i}. If S(i) is not empty, let f(i) be the maximum integer in S(i); otherwise, f(i) = i. Now we define bi as a f(i). Similarly, let T(i) = {j|i<j<=n, and a j is a multiple of a i}. If T(i) is not empty, let g(i) be the minimum integer in T(i); otherwise, g(i) = i. Now we define c i as ag(i). The boring sum of this sequence is defined as b 1 * c 1 + b 2 * c 2 + … + b n * c n

Given an integer sequence, your task is to calculate its boring sum.
 

Input

The input contains multiple test cases. 

Each case consists of two lines. The first line contains an integer n (1<=n<=100000). The second line contains n integers a 1, a2, …, a n (1<= a i<=100000). 

The input is terminated by n = 0.
 

Output

Output the answer in a line.
 

Sample Input

5 1 4 2 3 9 0
 

Sample Output

136


题意:对每个a[i],找a[i]往左第一个是a[i]倍数的数a[j],记b[i]=a[j],如没有就b[i]=a[i],

对每个a[i],找a[i]往右第一个是a[i]倍数的数a[j],记c[i]=a[j],如没有就c[i]=a[i];之后把

所有b[i]*c[i]相加,输出结果。


思路:从左往右扫a[],用数组yin[]下标表示a[i]因子,如扫到a[2]=4时,yin[1]=yin[2]=yin[4]=a[2];

这样扫到a[3]=2时;如yin[a[3]]!=0,则b[3]=yin[a[3]],否则b[3]=a[3].求c[]就把yin[]清零后从右往左

扫a[]。


#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
const int MAXN=100000+10;
#define ms(x,y) memset(x,y,sizeof(x))
using namespace std;
int a[MAXN];
int b[MAXN];
int c[MAXN];
int yin[MAXN];

void cal(int x)
{
	for(int i=1; i*i<=x; i++)
		if(x%i==0){yin[i]=yin[x/i]=x;}
}

int main()
{
	//freopen("in.txt","r",stdin);
	int n;
	while(scanf("%d", &n), n)
	{
		ms(yin,0);
		ms(b,0);
		ms(c,0);
		int i;
		for(i=1; i<=n; i++) scanf("%d", a+i);
		for(i=1; i<=n; i++){
			if(yin[a[i]]) b[i]=yin[a[i]];
			else b[i]=a[i];
			cal(a[i]);
		}
		ms(yin,0);
		for(i=n; i>=1; i--){
			if(yin[a[i]]) c[i]=yin[a[i]];
			else c[i]=a[i];
			cal(a[i]);
		}
		long long sum=0;
		for(i=1; i<=n; i++)
			sum+=(long long)b[i]*c[i];
		printf("%I64d\n",sum);
	}
	return 0;
}





数论——HDU 4961