我最初以为这是大树乘除法问题,后来发现只是普通的求最小公倍数方法。
原题:
Least Common Multiple
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 38411 Accepted Submission(s): 14484
Problem Description
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105.
Input
Input will consist of multiple problem instances. The first line of the input will contain a single integer indicating the number of problem instances. Each instance will consist of a single line of the form m n1 n2 n3 ... nm where m is the number of integers
in the set and n1 ... nm are the integers. All integers will be positive and lie within the range of a 32-bit integer.
Output
For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.
Sample Input
2 3 5 7 15 6 4 10296 936 1287 792 1
Sample Output
105 10296
wa码
#include<stdio.h> #include<stdlib.h> #include<algorithm> #include<string.h> #define max 100 using namespace std; int cmp(int a,int b) { return b<a; } long long a[max],s; int m,n,i,j; int main() { scanf("%d",&n); while(n--) { s=1; <span style="white-space:pre"> </span>scanf("%d",&m); for(i=0;i<m;i++) scanf("%d",&a[i]); sort(a,a+m,cmp); for(i=0;i<m;i++) { for(j=i+1;j<m;j++) { if((a[i]%a[j])==0) a[j]=1; } } for(i=0;i<m;i++) s=s*a[i]; printf("%d\n",s); } return 0; }
总是出错,于是改啊改,发现算法就是错的,我的只能算15 5 7,正好谁是谁的公倍数的,却算不来哦36 8 14这种(此时虽然8 14不能被36 整除,但是他们存在最大公约数),要用我的算法,应该等于36*14*8,显然不对!
我的AC码
<span style="font-size:24px;">#include<stdio.h> #include<stdlib.h> #include<algorithm> #include<string.h> #define max 100 int main() { int a,n,m,i,s; scanf("%d",&n); while(n--) { s=0; scanf("%d",&m); while(m--) { scanf("%d",&a); if(s==0)//</span><span style="font-size:14px;">先初始化让s西安等于第一个数的值</span><span style="font-size:24px;"> s=a; for(i=s; ; i=i+s)//</span><span style="font-size:14px;">特别巧妙的算法,用i每次都乘以整数倍的本身,当i被a整除时恰好i是两者的最大公倍数 {</span><span style="font-size:24px;"> if(i%a==0) break; } } printf("%d",s); } return 0; } </span>
意外收获:
误以为qort(a,n,sizeof(a0),cmp)
int cmp (const void *a,const void *b)
可以用在c和c++都行!
原来这个是c语言的
c++应该是
qsort(a,a+n,cmp)
int cmp (int a,int b)
return a<b 或者a>b
版权声明:本文为博主原创文章,未经博主允许不得转载。