4437: Carries
Submit your solution Discuss this problem Best solutions |
Carriesfrog has n integers a1,a2,…,an , and she wants to add them pairwise. Unfortunately, frog is somehow afraid of carries (进位). She defines hardness for adding x and y the number of carries involved in the calculation. For example, . Find the total hardness adding n integers pairwise. In another word, find
∑1≤i<j≤nh(ai,aj)
InputThe input consists of multiple tests. For each test: The first line contains 1 integer n ( 2≤n≤105 ). The second line contains n integers a1,a2,…,an . ( 0≤ai≤109 ). OutputFor each test, write 1 integer which denotes the total hardness. Sample Input Sample Output |
题意:给定n个数的序列,问这个序列任意两个数相加需要进的位数的和是多少;
思路:
1.给定两个数若这两个数的第k位相加会进位,则满足:(a%10^k+b%10^k)>=10^k;
2.按位计算贡献(进位次数);
3.题目要求是每两个只选择一次,但排序后并不影响,并不会重复枚举两个数;
样例:
97 56
56 97
123 123 //更换顺序后不会影响统计贡献(进位次数);
代码:
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=100005;
int a[maxn],b[maxn];
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int mod=1;
ll ans=0;
for(int i=1;i<=9;i++)
{
mod*=10;
for(int i=1;i<=n;i++)
b[i]=a[i]%mod;
sort(b+1,b+n+1);
for(int i=1;i<n;i++)
ans+=n-(lower_bound(b+i+1,b+n+1,mod-b[i])-b-1);
}
printf("%lld\n",ans);
}
return 0;
}