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

B. Carries

Time Limit: 1000ms
Memory Limit: 65536KB
64-bit integer IO format: %lld      Java class name: Main
Submit Status
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);
	}
}


你可能感兴趣的:(BNUoj Carries 统计进位的次数(优化))