51Nod 1305 Pairwise Sum and Divide | 思維 數學
阿新 • • 發佈:2017-09-01
time inf 最終 範圍 F12 %d com bsp art
Output
輸出fun(A)的計算結果。Input示例
3 1 4 1Output示例
4
first try:
#include "bits/stdc++.h" using namespace std; #define LL long long #define INF 0x3f3f3f3f3f #define PI acos(-1) #define N 100010 #define MOD 10 LL arr[N]; LL fun(int n){ LL sum=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ sum+=floor((arr[i]+arr[j])/(arr[i]*arr[j])); } } return sum; } int main() { int n; while(~scanf("%d",&n)){ for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } LL ans=fun(n); printf("%d\n",ans); } return 0; }
time limit exceeded
second try:
(a + b)/ab = 1/a + 1/b a>2且b>2時 不等式(a+b)/ab < 1 a,b不全為2時等號成立
取整後為0 , 所以只用查找1和2,以及>=2的個數即可
公式:sum = 2(N1-1)*N1/2 + N1*(∑Nk k>=2) + N2*(N2-1)/2
#include "bits/stdc++.h" using namespace std; #define LL long long #define INF 0x3f3f3f3f3f #define PI acos(-1) #define N 100010 #define MOD 10 intx,n; int one, two, other; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &x); if (x == 1) one++; if (x == 2) two++; if (x >= 2) other++; } LL sum = 0; sum += (one-1)*one + one*other + ( (two*(two-1))>>1 ); printf("%lld\n", sum); return 0; }
another:
1、觀察算式:floor(A+B)/(A*B),不難發現,如果其中A.B都是>=2的數值,那麽對應的值一定是0.那麽根據這個特性我們繼續討論:
①如果A=1&&B=1,那麽值為2,
②如果A=1||B=1&&另外一個不是1,那麽值為1,
③如果A=2&&B=2,那麽值為1.
根據以上特性,我們肯定是要來判斷a【i】==1||a【i】==2的個數來決定結果。
2、對於每一個1,我們考慮,其貢獻出來的值為:n-1,那麽我們一層for掃這個數組,如果有一個1,那麽對應結果加上n-1.
接下來我們統計2的個數,對應在最終結果上加:(cont2-1+1)*(cont2-1)/2;
3、數據範圍比較大, 註意使用LL.
#include<stdio.h> #include<string.h> using namespace std; #define ll __int64 int main() { int n; while(~scanf("%d",&n)) { ll cont2=0; ll output=0; for(int i=0;i<n;i++) { int x; scanf("%d",&x); if(x==1) { output+=n-1; } if(x==2) { cont2++; } } printf("%I64d\n",output+(cont2)*(cont2-1)/2); } }
http://www.cnblogs.com/whileskies/p/7220026.html
http://www.voidcn.com/article/p-pymuhyiw-da.html
51Nod 1305 Pairwise Sum and Divide | 思維 數學