BNUoj Carries 统计进位的次数(优化)

本文深入探讨了青蛙加法问题中进位的数学逻辑,通过实例和代码实现,揭示了如何计算多个整数两两相加时的进位总数。适合对算法、数学和编程感兴趣的读者深入学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

B. Carries

Time Limit: 1000ms
Memory Limit: 65536KB
64-bit integer IO format: %lld      Java class name: Main
frog has n integers a1,a2,,an , and she wants to add them pairwise.
 
Unfortunately, frog is somehow afraid of carries (进位). She defines \emph{hardness} h(x,y) for adding x and y the number of carries involved in the calculation. For example, h(1,9)=1,h(1,99)=2 .
 
Find the total hardness adding n integers pairwise. In another word, find
1i<jnh(ai,aj)
.

Input

The input consists of multiple tests. For each test:
 
The first line contains 1 integer n ( 2n105 ). The second line contains n integers a1,a2,,an . ( 0ai109 ).

Output

For each test, write 1 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
 

题意就是让统计出

1i<jnh(ai,aj)
满足此式子的数,h(ai,aj)表示ai与aj相加 各个位是否需要进位,需要进位就加1,表示此位数需要进位.

h(999,999)=3;

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<algorithm>

using namespace std;

int a[100010],b[100010];
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
		}
		long long sum=0;

		for(int k=10;k<=1000000000;k*=10)  //表示第几位
		{
			for(int i=0;i<n;i++)
			{
				b[i]=a[i]%k;     //进位与尾数有关
			}
			sort(b,b+n);
			for(int i=n-1,j=0;i>=0;i--)
			{
				while(i>j&&(long long)(b[i]+b[j])<k) //消除不进位的数
					j++;
				if(i<=j)
					break;
				sum+=i-j;
			}
		}
		printf("%lld\n",sum);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值