标签:
二分法听起来并不陌生,早在高中就有提到,比如找到一段电线中那里断路就要从中间向两边找,然后在把断的那一面分成两段…这样就能节省时间了.那么在计算机中的二分法也是如此,面对庞大的数据也能很快的找出来。但在运用上灵活多变,一定要善于运用,以下是两个二分法查找的的两个题,及代码;
Description
Input
Output
Sample Input
Sample Output
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int a[100005]; int main() { int t,n,m,i,j,k; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&k); for(i=1; i<=n; i++) scanf("%d",&a[i]); a[0]=-1; sort(a,a+n+1); int ans=0; int big,small; int mid; for(i=1; i<=n; i++) { if(a[i-1]!=a[i]) { big=n; small=1; while(small<=big) { mid=(big+small)/2; if(a[mid]+a[i]==k) { ans++; break; } if(a[mid]+a[i]>k) big=mid-1; else small=mid+1; } } } printf("%d\n",ans); } return 0; }
Description
Input
Output
Sample Input
Sample Output
#include <iostream> #include <stdio.h> #include <algorithm> #define ll long long using namespace std; ll n,a[20005],b[20005],c[20005]; ll search(ll mid) { ll k,sum=0; for(int i=0; i<n; i++) { k=min(mid,b[i]); if(k>=a[i]) sum+=(k-a[i])/c[i]+1; } return sum; } int main() { while(~scanf("%d",&n)) { for(int i=0; i<n; i++) scanf("%lld%lld%lld",&a[i],&b[i],&c[i]); ll L=0; ll R=1LL<<31; ll mid; while(L<R) { mid=(L+R)/2; if(search(mid)%2) R=mid; else L=mid+1; } if(L==1LL<<31) printf("DC Qiang is unhappy.\n"); else printf("%lld %lld\n",L,search(L)-search(L-1)); } return 0; }
标签:
原文地址:http://www.cnblogs.com/yuanbo123/p/4725190.html