frog has nn integers a1,a2,…,ana1,a2,…,an, and she wants to add them pairwise.
Unfortunately, frog is somehow afraid of carries (进位). She defines hardness h(x,y)h(x,y)for adding xx and yy the number of carries involved in the calculation. For example, h(1,9)=1,h(1,99)=2h(1,9)=1,h(1,99)=2.
Find the total hardness adding nn integers pairwise. In another word, find
∑1≤i<j≤nh(ai,aj)∑1≤i<j≤nh(ai,aj)
.
Input
The input consists of multiple tests. For each test:
The first line contains 11 integer nn (2≤n≤1052≤n≤105). The second line contains nnintegers a1,a2,…,ana1,a2,…,an. (0≤ai≤1090≤ai≤109).
Output
For each test, write 11 integer which denotes the total hardness.
Sample Input
2
5 5
10
0 1 2 3 4 5 6 7 8 9
Sample Output
1
20
题意:第一行一个n代表第二行输入数字的个数。问使这些数字两两相加,总共可以进多少位。
思路:比赛时真的是没什么思路,满脑子都是暴力(暴力流天下第一)。下来后看题解才知道有这么一个进位公式
如果2个数a,b的第k位相加要进位,那么必须满足(a%10^k+b%10^k)>=10^k
有这个公式就好办了,题目给的数的范围是<=10^9,也就是说我们要枚举9位。之后再开一个数组b[]存原来的数字%k之后的值。然后进行从小到大排序,如果b[n-1]大于等于(k-b[i])说明又可以进位的,之后进行二分查找
注意数据范围,要开long long 的不然会WA
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int a[100005],b[100005];
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
long long sum=0,k=1;
for(int i=1; i<=9; i++)
{
k*=10;
for(int j=0; j<n; j++)
b[j]=a[j]%k;
sort(b,b+n);
for(int j=0; j<n; j++)
{
long long q=k-b[j];
if(b[n-1]>=q)
{
int num=lower_bound(b,b+n,q)-b;
if(num>j)
sum+=n-num;
else
sum+=n-(j+1);
}
}
}
printf("%lld\n",sum);
}
}