上海交通大学计算机考研复试 2008年(java)

问题一:
题目描述

Output the k-th prime number.

输入描述:

k≤10000

输出描述:

The k-th prime number.

示例1
输入

3
7

输出

5
17

解法一:

import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
    public static void main(String[] args) throws ParseException{
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
	        String str;
	        while((str=br.readLine()) != null) {
                int num = Integer.parseInt(str);
                boolean[] isNotPrime = new boolean[150000];
                for (int i = 2; i < 150000; i++) {
                    if (!isNotPrime[i]) {
                        for (int j = 2 * i;j < 150000; j += i) {
                            isNotPrime[j] = true;
                        } 
                    }
                } 
	        	int count = 0;
	        	int n = 2;
	        	while(count <= num) {
	        		if(!isNotPrime[n]) {
	        			count++;
	        			if(count == num) break;
	        		}
	        		n++;
	        	}
	        	System.out.println(n);
	        }
 	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
}

解法二:

import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
    public static void main(String[] args) throws ParseException{
        try {
            BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
            String str;
            while((str=br.readLine()) != null) {
                int num = Integer.parseInt(str);
                int count = 0;
                int n = 2;
                while(count <= num) {
                    if(isPrime(n)) {
                        count++;
                        if(count == num) break;
                    }
                    n++;
                }
                System.out.println(n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static boolean isPrime(int a) {
            
        if (a < 2) {// 素数不小于2
            return false;
        } else {
  
            for (int i = 2; i <= Math.sqrt(a); i++) {
  
                if (a % i == 0) {// 若能被整除,则说明不是素数,返回false
  
                    return false;
                }
            }
        }
        return true;
    }
}

问题二:
题目描述

You are given an unsorted array of integer numbers. Your task is to sort this array and kill possible duplicated elements occurring in it.

输入描述:

For each case, the first line of the input contains an integer number N representing the quantity of numbers in this array(1≤N≤1000). Next N lines contain N integer numbers(one number per each line) of the original array.

输出描述:

For each case ,outtput file should contain at most N numbers sorted in ascending order. Every number in the output file should occur only once.

示例1
输入

6
8 8 7 3 7 7

输出

3 7 8
import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
    public static void main(String[] args){
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
	        String str;
	        while((str = br.readLine()) != null) {
	        	int n = Integer.parseInt(str);
	        	int[] nums = new int[n];
	        	String[] parts = br.readLine().split(" ");
	        	for(int i = 0; i < n; i++) {
	        		nums[i] = Integer.parseInt(parts[i]);
	        	}
	        	Arrays.sort(nums);
	        	int count = 0;
	        	for(int i = 0; i < n; i++) {
	        		while(i+1 < n && nums[i] == nums[i+1]) i++;
	        		nums[count++] = nums[i];
	        	}
	        	System.out.print(nums[0]);
	        	for(int i = 1; i < count; i++) {
	        		System.out.print(" "+nums[i]);
	        	}
	        	System.out.println();
	        }
 	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
}

问题三:
题目描述

Find a longest common subsequence of two strings.

输入描述:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出描述:

For each case, output k – the length of a longest common subsequence in one line.

示例1
输入

abcd
cxbydz

输出

2

问题四:
题目描述

We now use the Gregorian style of dating in Russia. The leap years are years with number divisible by 4 but not divisible by 100, or divisible by 400. For example, years 2004, 2180 and 2400 are leap. Years 2005, 2181 and 2300 are not leap. Your task is to write a program which will compute the day of week corresponding to a given date in the nearest past or in the future using today’s agreement about dating.

输入描述:

There is one single line contains the day number d, month name M and year number y(1000≤y≤3000). The month name is the corresponding English name starting from the capital letter.

输出描述:

Output a single line with the English name of the day of week corresponding to the date, starting from the capital letter. All other letters must be in lower case.

Month and Week name in Input/Output:
January, February, March, April, May, June, July, August, September, October, November, December
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

示例1
输入

9 October 2001
14 October 2001

输出

Tuesday
Sunday
import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
	static HashMap<String, Integer> mon1 = new HashMap<>();
	static HashMap<String, Integer> mon2 = new HashMap<>(); 
    public static void main(String[] args){
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    		mon1.put("January", 0);
    		mon1.put("February", 31);
    		mon1.put("March", 59);
    		mon1.put("April", 90);
    		mon1.put("May", 120);
    		mon1.put("June", 151);
    		mon1.put("July", 181);
    		mon1.put("August", 212);
    		mon1.put("September", 243);
    		mon1.put("October", 273);
    		mon1.put("November", 304);
    		mon1.put("December", 334);
    		mon2.put("January", 0);
    		mon2.put("February", 31);
    		mon2.put("March", 60);
    		mon2.put("April", 91);
    		mon2.put("May", 121);
    		mon2.put("June", 152);
    		mon2.put("July", 182);
    		mon2.put("August", 213);
    		mon2.put("September", 244);
    		mon2.put("October", 274);
    		mon2.put("November", 305);
    		mon2.put("December", 335);
    		String[] date = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    		String str;
    		while((str = br.readLine()) != null) {
    			String[] parts = str.split(" ");
    			System.out.println(date[getDay(Integer.parseInt(parts[2]), parts[1], Integer.parseInt(parts[0]))%7]);
    		}
 	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
    public static int getDay(int year, String month, int day) {
    	int sum = 0;
    	for(int i = 1; i < year; i++) {
    		if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) sum += 366;
    		else sum += 365;
    	}
    	if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) sum += mon2.get(month);
    	else sum += mon1.get(month);
    	sum += day;
    	return sum;
    }
}

问题五:
题目描述

We are all familiar with pre-order, in-order and post-order traversals of binary trees. A common problem in data structure classes is to find the pre-order traversal of a binary tree when given the in-order and post-order traversals. Alternatively, you can find the post-order traversal when given the in-order and pre-order. However, in general you cannot determine the in-order traversal of a tree when given its pre-order and post-order traversals. Consider the four binary trees below:

All of these trees have the same pre-order and post-order traversals. This phenomenon is not restricted to binary trees, but holds for general m-ary trees as well.

输入描述:

Input will consist of multiple problem instances. Each instance will consist of a line of the form m s1 s2, indicating that the trees are m-ary trees, s1 is the pre-order traversal and s2 is the post-order traversal.All traversal strings will consist of lowercase alphabetic characters. For all input instances, 1 <= m <= 20 and the length of s1 and s2 will be between 1 and 26 inclusive. If the length of s1 is k (which is the same as the length of s2, of course), the first k letters of the alphabet will be used in the strings. An input line of 0 will terminate the input.

输出描述:

For each problem instance, you should output one line containing the number of possible trees which would result in the pre-order and post-order traversals for the instance. All output values will be within the range of a 32-bit signed integer. For each problem instance, you are guaranteed that there is at least one tree with the given pre-order and post-order traversals.

示例1
输入

2 abc cba
2 abc bca
10 abc bca
13 abejkcfghid jkebfghicda

输出

4
1
45
207352860
import java.io.*;
 
public class Main {
    private static long num = 1;
    private static long numArr[];
    static int n;
    public static void main(String[] args) throws Exception {
        initArr();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = br.readLine()) != null) {
        	String[] parts = str.split(" ");
            n = Integer.parseInt(parts[0]);
            String preOrder = parts[1];
            String postOrder = parts[2];
            num = 1;
            CaculateTree(preOrder, postOrder);
            System.out.println(num);
        }
    }
    private static void CaculateTree(String preOrder, String postOrder) {
        int len = preOrder.length();
        if (len == 1) {
            return;
        }
        int count = 0;
        preOrder = preOrder.substring(1);//先序遍历除根节点外的结点
        postOrder = postOrder.substring(0,len-1);//后序遍历除根节点外的结点
        while (!"".equals(preOrder)) {
            int index = postOrder.indexOf(preOrder.charAt(0))+1;//后序遍历中先序遍历第一次出现的位置
            //意味着从0到这一部分是第一棵子树
            String newPre = preOrder.substring(0,index);
            String newPost = postOrder.substring(0,index);
            preOrder = preOrder.substring(index);
            postOrder = postOrder.substring(index);
            count++;//计算一共有多少棵子树
            CaculateTree(newPre, newPost);//然后子树的子树再继续进行计算
        }
        num *= CaculateCom(count);//sum = sum0*sum1*sum2*sum3*……sumk
    }
    //排列方法数求解
    private static void initArr() {
        numArr = new long[21];
        numArr[0] = 1;
        for (int i = 1; i < 21; i++) {
            numArr[i] = numArr[i - 1] * i;
        }
    }
    private static long CaculateCom(int m) {
        return numArr[n] / (numArr[n - m] * numArr[m]);//n!/((n-m)!*m!)
    }
}
发布了332 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104975348
今日推荐