(Java)の半分_Aggressivecows、半分は_方程式の根半分、数字のペアを見つけるために_

package 蓝桥杯;

import java.util.Arrays;
import java.util.Scanner;

public class VO二分_Aggressivecows  {

	static int N,C;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner reader=new Scanner(System.in);
		N=reader.nextInt();
		C=reader.nextInt();
		int[] a=new int[N];
		int Nb=N;
		int l=0;
		while(Nb!=0) {
			a[l++]=reader.nextInt();
			Nb--;
		}
		Arrays.sort(a);//对输入的隔间坐标进行快速排序,时间复杂度是log(N);
		System.out.println(BinaryTree(a));//二分法寻找D
	}
	static int BinaryTree(int[] a) {
		int L=1,R=1000000000/C,maxD=0;
		int D=(L+R)/2;
		while(L<=R) {//二分法找最大最小距离D,时间复杂度是log(1000000000/C)
			if(D_can(a,D)) {
				maxD=D;
				L=D+1;
			}
			if(!D_can(a,D)) {
				R=D-1;
			}
			D=(L+R)/2;
		}
		return maxD;
		
	}
	
	static boolean D_can(int[] a,int D) {
		int count=1;//标记已经放了多少头牛
		int Db=a[0]+D;//第2头牛至少要放在Db之后的位置。
		for(int i=1;i<C;i++) {//第1头牛放在a[0],所以少放1头牛,下标从1开始。
			for(int j=count;j<N;j++) {//无需从j=0开始循环,因为前面放过牛的地方就可以不用判断了。//时间复杂度是隔间的个数N
				if(a[j]>=Db) {//判断是否有隔间的坐标符合。
					count++;
					Db=a[j]+D;//更新下个隔间的坐标。
					break;//一旦找出符合要求的第一个隔间就结束判断。
				}
			}
		}
		if(count==C) return true;
		else return false;
	}

}
//测试数据:5 3 1 2 5 8 9 
package 蓝桥杯;

import java.util.Arrays;
import java.util.Scanner;

public class VO二分_找一对数 {
	public static void main(String[] args) {
		Scanner reader=new Scanner(System.in);
		int n=reader.nextInt();
		int N=n;
		int i=1,m;
		int[] a=new int[n+1];
		while(n!=0) {
			a[i++]=reader.nextInt();
			n--;
		}
		m=reader.nextInt();
		Arrays.sort(a);
		int x1=1,x2=N;
		while(x1<x2&&a[x1]+a[x2]!=m) {
			if(a[x1]+a[x2]>m)
				x2--;
			else x1++;
		}
		if(x1==x2)
			System.out.println("No");
		else
		System.out.println(a[x1]+" "+a[x2]);
		reader.close();
	}

}

package 蓝桥杯;
public class VO二分_方程的根 {

	public static void main(String[] args) {
		System.out.printf("%.6f",BinaryTree());
	}
	static double f(double x) {
		return x*x*x*x*x-15*x*x*x*x+85*x*x*x-225*x*x+274*x-121;
	}
	static double EPS=1e-6;
	static double BinaryTree() {
		double x1=1.5,x2=2.4,root;
		root=x1+(x2-x1)/2;
		double t=f(root);
		
		while(Math.abs(t)>=EPS) {
			if(t>0) x1=root;
			else    x2=root;
			root=x1+(x2-x1)/2;
			t=f(root);
			
		}
		return root;
	}

}

公開された20元の記事 ウォンの賞賛1 ビュー414

おすすめ

転載: blog.csdn.net/XMY_UPUPUP/article/details/104723779