SCU - 4437 Carries (思维+二分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chimchim04/article/details/89492486

Carries

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个数,问所有两两相加,总共的进位次数

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int N=100005;
ll a[N],b[N],l[20]={1};
int main()
{
    for(int i=1;i<=10;i++)
        l[i]=l[i-1]*10;
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)
            scanf("%lld",&a[i]);
        ll ans=0;
        for(int j=1;j<=10;j++)
        {
            for(int i=0;i<n;i++)
                b[i]=a[i]%l[j];
            sort(b,b+n);
            for(int i=0;i<n;i++)
            {
                int li=i+1,r=n,mid,k=n;
                while(li<=r)
                {
                    mid=(li+r)/2;
                    if(b[mid]+b[i]>=l[j]) {r=mid-1;k=mid;}
                    else li=mid+1;
                }
                ans+=(n-k);
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chimchim04/article/details/89492486