@ZHANGQIANYI2020
HNUCM-OJ 归并排序,大整数乘法,第k小元素问题,第k大元素问题,前m大数,找中位数
问题 A: 归并排序
(时间限制: 1 Sec 内存限制: 256 MB)
题目描述:
编写一个程序,使用分治策略实现二路归并排序(升序)。
输入:
多组输入,每组第一个数字为数组长度,然后输入一个一维整型数组。
输出:
输出排序之后(升序)的一维整型数组,每组输出占一行。
样例输入:
6 1 8 6 5 3 4
5 12 42 2 5 8
样例输出:
1 3 4 5 6 8
2 5 8 12 42
参考答案:
import java.util.Scanner;
public class Main {
public static void sort(int []arr){
int []temp = new int[arr.length];
sort(arr,0,arr.length-1,temp);
}
private static void sort(int[] arr,int left,int right,int []temp){
if(left<right){
int mid = (left+right)/2;
sort(arr,left,mid,temp);
sort(arr,mid+1,right,temp);
merge(arr,left,mid,right,temp);
}
}
private static void merge(int[] arr,int left,int mid,int right,int[] temp){
int i = left;
int j = mid+1;
int t = 0;
while (i<=mid && j<=right){
if(arr[i]<=arr[j]){
temp[t++] = arr[i++];
}else {
temp[t++] = arr[j++];
}
}
if(i>mid){
for(int q=j;q<=right;q++)
temp[t++] = arr[q];
}else{
for(int q=i;q<=mid;q++)
temp[t++] = arr[q];
}
t = 0;
while(left <= right){
arr[left++] = temp[t++];
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
sort(a);
for(int i=0;i<n;i++) {
System.out.print(a[i]+" ");
}
}
}
}
问题 B: 大整数乘法
(时间限制: 1 Sec 内存限制: 128 MB)
题目描述:
使用分治算法实现两个大整数相乘。
输入:
两个十进制大整数,满足每一个整数长度为2^n且两个大整数的长度相等。(多组数据)
输出:
两个大整数的乘积。
样例输入:
1234 5678
样例输出:
7006652
参考答案:
import java.util.Scanner;
public class Main {
public static long zhengshucheng(long x,long y,int n) {
int signx=(x<0?-1:1);
int signy=(y<0?-1:1);
int sign=signx*signy;
x=Math.