模数之和
Problem Statement
You are given N positive integers a_1, a_2, ..., a_N.
For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).
Here, X\ mod\ Y denotes the remainder of the division of X by Y.
Find the maximum value of f.
Constraints
- All values in input are integers.
- 2 \leq N \leq 3000
- 2 \leq a_i \leq 10^5
Input
Input is given from Standard Input in the following format:
N a_1 a_2 ... a_N
Output
Print the maximum value of f.
Sample Input 1
3 3 4 6
Sample Output 1
10
f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.
Sample Input 2
5 7 46 11 20 11
Sample Output 2
90
Sample Input 3
7 994 518 941 851 647 2 581
Sample Output 3
4527
一开始,猜想n个数的最小公倍数-1,即为m
用m去mod 数组的每一个数,最后加一起就好了
于是乎这么做了
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <vector>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include <cstdio>
#include <queue>
#include<stack>
using namespace std;
int gcd(int a, int b)
{
while (b)
{
int c = a;
a = b;
b = c%b;
}
return a;
}
long long gongbeishu(long long a, long long b)
{
long long d = gcd(a, b);
return a*b / d;
}
int main() {
int n;
long long x;
cin >> n;
int * a = new int[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
x = a[0];
for (int i = 1; i < n; i++)
{
x = gongbeishu(a[i], x);
}
x--;
long long s = 0;
for (int j = 0; j < n; j++)
s += x%a[j];
cout << s;
system("pause>nul");
return 0;
}
前面两组数字小的,顺利通过
然而,最后一个,,,,
最后一组数据,x求不出来,溢出了
就查吖,溢出怎么办
改成long long 也不行
好吧,我不会处理了,看看大神怎么处理的吧,是不是特别强
结果就一个循环
for (int j = 0; j < n; j++)
s += a[j]-1;
cout << s;
更加离奇了是不是?
哈哈,其实从第一步猜想开始,就已经得到了这个方法
最小公倍数,想想啊,模取每一个数,结果就是这个数-1啊
豁然开朗,豁然开朗,在已经知道结果的情况下,我还去算个鬼啊?