XMU 1608 nc与加法进位 【二分】

1608: nc与加法进位

Time Limit: 2000 MS  Memory Limit: 128 MB
Submit: 29  Solved: 27
[Submit][Status][Web Board]

Description

nc最近很无聊~所以他总是想各种有趣的问题来打发时间。
nc喜欢做加法运算,他对加法进位很感兴趣。现在给你n个数字,他想知道,这些数字两两相加,一共会出现多少次加法进位。

Input

第一行包含1个整数n,表示有n个数字。(n<=5000)
第二行包含n个数字,分别表示a1,a2,...an。(0 ≤ai ≤ 10^9).

Output

这些数字两两相加,出现加法进位次数。

Sample Input

3
43 58 85

Sample Output

5

HINT

 

Source

[Submit][Status][Web Board]

题目链接:

  http://acm.xmu.edu.cn/JudgeOnline/problem.php?id=1608

题目大意:

  题目给出N个数,问这些数两两相加共会出现几次加法进位。

题目思路:

  【二分】

  N最大5000,其实这题直接拿高精度加法统计就能过,而且0ms,数据不算很强。

  NlogN的做法N可以达到10W。

  首先可以假设这N个数位数都相同(不足补0)

  枚举每一位(k=1~8),对于当前的这一位,将N个数按照当前这一位上数字从小到大排序。

  再枚举每个数,假设第i个数在第k位为x,则二分其余N-1个数这一位>=10-x的个数,加到答案上。

  (针对每一位去统计进位次数)

  这样时间复杂度降到NlogN。

  

 1 /****************************************************
 2      
 3     Author : Coolxxx
 4     Copyright 2017 by Coolxxx. All rights reserved.
 5     BLOG : http://blog.csdn.net/u010568270
 6      
 7 ****************************************************/
 8 #include<bits/stdc++.h>
 9 #pragma comment(linker,"/STACK:1024000000,1024000000")
10 #define abs(a) ((a)>0?(a):(-(a)))
11 #define lowbit(a) (a&(-a))
12 #define sqr(a) ((a)*(a))
13 #define mem(a,b) memset(a,b,sizeof(a))
14 const double EPS=1e-8;
15 const int J=10;
16 const int MOD=100000007;
17 const int MAX=0x7f7f7f7f;
18 const double PI=3.14159265358979323;
19 const int N=5004;
20 const int M=14;
21 using namespace std;
22 typedef long long LL;
23 double anss;
24 LL aans;
25 int cas,cass;
26 int n,m,lll,ans;
27 int e[]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
28 int a[N],b[N];
29 int main()
30 {
31     #ifndef ONLINE_JUDGE
32     freopen("1.txt","r",stdin);
33 //  freopen("2.txt","w",stdout);
34     #endif
35     int i,j,k;
36     int x,y,z;
37 //  for(scanf("%d",&cass);cass;cass--)
38 //  for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
39 //  while(~scanf("%s",s))
40     while(~scanf("%d",&n))
41     {
42         for(i=1;i<=n;i++)
43             scanf("%d",&a[i]);
44         for(k=1;k<10;k++)
45         {
46             for(i=1;i<=n;i++)
47                 b[i]=a[i]%e[k];
48             sort(b+1,b+1+n);
49             for(i=1;i<=n;i++)
50             {
51                 int l,r,mid;
52                 l=i+1,r=n;
53                 while(l<=r)
54                 {
55                     mid=(l+r+1)/2;
56                     if(b[mid]+b[i]<e[k])l=mid+1;
57                     else r=mid-1;
58                 }
59                 aans+=n-r;
60             }
61         }
62         printf("%lld
",aans);
63     }
64     return 0;
65 }
66 /*
67 //
68  
69 //
70 */
View Code
原文地址:https://www.cnblogs.com/Coolxxx/p/6753495.html