Day 25 算法笔记之算法初步4.5 二分(2)

1.Shopping in mars

j的用法很细节

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

int n,m;
int martix[1000];

int find(int l,int m){
	int left=l,right=n+1,mid;
	int goal = martix[l-1]+m;
	
	while(left<right){
		printf("%d %d\n",left,right);
		mid = (left+right)/2;
		if(martix[mid]>goal){
			right = mid;
		}else{
			left = mid + 1;
		}
	}
	printf("%d %d\n",left,right);
	return left;
}

int find2(int l,int m){
	int left=l,right=n+1,mid;
	int goal = martix[l-1]+m;
	
	while(left<right){
		mid = (left+right)/2;
		if(martix[mid]>goal){
			right = mid;
		}else{
			left = mid + 1;
		}
	}
	return left;
}

int main(){
	scanf("%d %d",&n,&m);
	
	int temp;
	for(int i=1;i<=n;i++){
		scanf("%d",&temp);
		martix[i] = martix[i-1] + temp;
	}
	
	int value,gap;
	for(int i=1;i<=n;i++){
		int j = find(i,m);//大于m的第一个 
		gap = martix[j-1] - martix[i-1];
		if(gap==m){
			value = m;
			break;
		}else if(j<=n){
			value = min(value,gap);
		}
	}
	
	for(int i=1;i<=n;i++){
		int j = find2(i,value);
		if(martix[j-1]-martix[i-1]==value){
			printf("%d-%d\n",i,j-1);
		}
		
	}

	return 0;
}

2.find coins

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

bool cmp(int a,int b){
	return a<b;
}


int martix[1000];
int f(int left,int right,int x){
	int mid;
	while(left<=right){
		mid = (left+right)/2;
		if(martix[mid]==x){
			return left;
		}else if(martix[mid]>x){
			right = mid -1;
		}else{
			left = mid + 1;
		}
	}
	return -1;
}

int main(){
	
	int n,m;
	scanf("%d %d",&n,&m);
	
	
	for(int i=0;i<n;i++){
		scanf("%d",&martix[i]);
	}
	
	sort(martix,martix+n,cmp);
	
	for(int i=0;i<n;i++){
		int j = f(0,n-1,m-martix[i]);
		if(j!=-1&&j!=i){
			if(i>j){
				int temp=i;
				i=j;
				j=temp;
			}
			printf("%d %d",martix[i],martix[j]);
			break;
		}
	}
	
	return 0;
}

おすすめ

転載: blog.csdn.net/aixiaoxiao13/article/details/120790996