西电软件工程算法分析与设计上机题

上机

代码仓库地址

代码地址:我的仓库

自己写的工具包说明

tools.AlgorithmTools

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class AlgorithmTools {

    public static boolean less(Comparable a, Comparable b){
        return a.compareTo(b) < 0;
    }

    public static boolean equal(Comparable a, Comparable b){
        return a.compareTo(b) == 0;
    }

    public static boolean larger(Comparable a, Comparable b){
        return a.compareTo(b) > 0;
    }

    public static void exchange(Comparable[] arr, int a, int b) throws IndexOutOfBoundsException{
        Comparable temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

    public static void exchange(ArrayList arrayList, int a, int b) throws IndexOutOfBoundsException{
        Object temp = arrayList.get(a);
        arrayList.set(a, arrayList.get(b));
        arrayList.set(b, temp);
    }

    public static Pair<Long, Object> timeLoggerProxy(Class clazz, String methodName, Object[] parameters, Class[] paraClazz)
            throws
            NoSuchMethodException,
            IllegalAccessException,
            InvocationTargetException {
        Method method = clazz.getMethod(methodName, paraClazz);
        long startTime = System.currentTimeMillis();
        Object result = method.invoke(parameters);
        long endTime = System.currentTimeMillis();
        return new Pair<>(startTime-endTime, result);
    }

    public static class Pair<K1, K2>{
        public K1 i;
        public K2 j;
        public Pair(){

        }

        public Pair(K1 i, K2 j){
            this.i = i;
            this.j = j;

        }

        @Override
        public int hashCode() {
            return i.hashCode() << 15 + j.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if(!(obj instanceof Pair)){
                return false;
            }

            Pair pair = (Pair)obj;

            if(this.i.equals(pair.i) && this.j.equals(pair.j))return true;

            return false;
        }
    }
}

函数功能
less通过调用CompareTo这个接口,返回“小的概念”
large类似,返回”大“的概念
equal类似,返回”等于“的概念
exchange交换数组中的数
timeLoggerProxy测量某个函数运行时间的代理,返回一个Pair<Long, Object>类型,一个是时间(ms),一个是函数调用返回结果
class Pair<K1, K2>在某些情况下可以复用的”数对“这一概念的类

第一次上机(分治)

1.Implement exercise 2.3-7.

2.Implement priority queue.

3.Implement Quicksort and answer the following questions. (1) How many comparisons will Quicksort do on a list of n elements that all have the same value? (2) What are the maximum and minimum number of comparisons will Quicksort do on a list of n elements, give an instance for maximum and minimum case respectively.

4.Give a divide and conquer algorithm for the following problem: you are given two sorted lists of size m and n, and are allowed unit time access to the ith element of each list. Give an O(lg m + lgn) time algorithm for computing the kth largest element in the union of the two lists. (For simplicity, you can assume that the elements of the two lists are distinct).

1.在数组中找到与两数之和相等的另外一个数

首先将数组排序(我是递减),在排序后的数组中,设置两个指针,分别指向数组头和数组尾
然后将两个指针指向的值之和sum与目标值tar比较,
若sum>tar:low++;
若sum<tar:high–;
相等则返回,low>high则没找到

2.优先队列

嗯,就是优先队列
核心就俩函数

/**
     * The function make the part of a unsorted heap to be partly sorted.
     * It make the index to be sorted.
     * For example:
     *          5
     *         / \
     *        4   3
     *       / \   \
     *      2   0   6(unsorted, run{@code swim(5)})
     *
     *      ------->
     *
     *          6
     *         / \
     *        4   5
     *       / \   \
     *      2   0   3
     * @param k input the index of the array to be resorted to be sorted.
     *
     *
     *
     * */
    private void swim(int k) {
        while(k > 0 && AlgorithmTools.less(arr.get(k/2), arr.get(k))){
            AlgorithmTools.exchange(arr, k/2, k);
            k = k / 2;
        }
    }
    /**
     *
     *The function make the part of a unsorted heap to be partly sorted.
     * It make the index to be sorted.
     * For example:
     *           5(unsorted, run{@code sink(0)})
     *          / \
     *         4   3
     *        / \   \
     *       2   0   6
     *
     *       ------->
     *
     *           6
     *          / \
     *         4   5
     *        / \   \
     *       2   0   3
     * @param k input the index of the array to be resorted to be sorted.
     *
     *
     *
     * */
    private void sink(int k){
        int size = arr.size();

        while(2 * k < size){
            int j = 2 * k;
            if(j < size - 1 && AlgorithmTools.less(arr.get(j), arr.get(j+1))) j++;
            if(!AlgorithmTools.less(arr.get(k), arr.get(j))) break;
            AlgorithmTools.exchange(arr, k, j);
            k = j;
        }
    }

代码说明已经写在javadoc里了

3.快排

略,相信都会

4.在两个数组的合并数组中找到第k大的值

参考文章:两个有序数组中找到第k大的元素

第二次上机(DP)

1.Matrix-chain product. The following are some instances.
a)❤️, 5, 2, 1,10>
b)<2, 7, 3, 6, 10>
c)<10, 3, 15, 12, 7, 2>
d)<7, 2, 4, 15, 20, 5>

2.Longest Common Subsequence (LCS). The following are some instances.
a)X: xzyzzyx Y: zxyyzxz
b)X:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCALLAAQANKESSSESFISRLLAIVAD
Y:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG

3.Longest Common Substring. The following are some instances.
a)X: xzyzzyx Y: zxyyzxz
b)X:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCALLAAQANKESSSESFISRLLAIVAD
Y:MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG

4.Max Sum. The following is an instance.
a)(-2,11,-4,13,-5,-2)

5.Shortest path in multistage graphs. Find the shortest path from 0 to 15 for the following graph.
A multistage graph is a graph (1) G=(V,E) with V partitioned into K >= 2 disjoint subsets such that if (a,b) is in E, then a is in Vi , and b is in Vi+1 for some subsets in the partition; and (2) | V1 | = | VK | = 1.
在这里插入图片描述

1.矩阵链乘积

参考 矩阵链乘法例题详解

2.最长公共子序列

private static String findLCS(String a,
                                  int aIndex,
                                  String b,
                                  int bIndex,
                                  Map<Pair<Integer, Integer>, String> memory){
        if(memory.containsKey(new Pair<Integer,Integer>(aIndex, bIndex))){
            return memory.get(new Pair<Integer,Integer>(aIndex, bIndex));
        }

        if(aIndex >= a.length())return "";
        if(bIndex >= b.length())return "";

        if(a.charAt(aIndex) == b.charAt(bIndex)){
            String result = a.charAt(aIndex) +
                    findLCS(a, aIndex + 1, b, bIndex + 1, memory);
            memory.put(new Pair<Integer,Integer>(aIndex, bIndex), result);
            return result;
        }
        else{
            String r1 = findLCS(a, aIndex + 1, b, bIndex, memory);
            String r2 = findLCS(a, aIndex, b, bIndex + 1, memory);
            String result = r1.length() > r2.length() ? r1 : r2;
            memory.put(new Pair<Integer,Integer>(aIndex, bIndex), result);
            return result;
        }
    }

javadoc我没写(懒),放这里说说
String a和b是你输入的两个串
aIndex和bIndex是一个检查到某位置的下标
memory是为了防止递归多次栈太深效率低下,memory记载aIndex和bIndex对应的返回值。
在检查串的某个位置时,若相等(在这匹配成功)则串a和串b都向前检查,递归调用。
若不等,分别检查a串向前一步和b串向前一步找到长的那个(子问题的最优解)记录返回即可

3.最长公共子串

解法我就不写了,网上一抓一大把
我就写写这个函数的参数:

private static String findLCS(String a,
                                  int aIndex,
                                  String b,
                                  int bIndex,
                                  Map<AlgorithmTools.Pair<Integer, Integer>, String> indexToStrMemory,
                                  Map<AlgorithmTools.Pair<Integer, Integer>, String> memory)

memory:类似上一个LCS的memory
indexToStrMemory:这个map两个位置指针为key,代表以这两个指针位置开始的最大公共串,前提是这两个位置上的字符一致

4.MaxSum

网上一抓一大把
参考链接

5.最短路径(Dijkstra)

迪杰斯特拉算法,缺点是只能处理边权值非负的情况
我给这个题目写了个Graph的类,用于封装此类问题,(后面的贝尔曼福特和弗洛伊德都用到)

第三次上机(贪心)

1.Knapsack Problem. There are 5 items that have a value and weight list below, the knapsack can contain at most 100 Lbs. Solve the problem both as fractional knapsack and 0/1 knapsack.

2.A simple scheduling problem. We are given jobs j1, j2… jn, all with known running times t1, t2… tn, respectively. We have a single processor. What is the best way to schedule these jobs in order to minimize the average completion time. Assume that it is a nonpreemptive scheduling: once a job is started, it must run to completion. The following is an instance.
a)(j1, j2, j3, j4) : (15,8,3,10)

3.Single-source shortest paths. The following is the adjacency matrix, vertex A is the source.
在这里插入图片描述
4.All-pairs shortest paths. The adjacency matrix is as same as that of problem 3.(Use Floyd or Johnson’s algorithm)

背包问题

可分背包

可分背包。。。把所有背包按(价值/重量)排序就行了

0-1背包

用一下动态规划。
写一个函数:对于某些物体,在背包容量为w的情况下总能返回最大可装价值

private static Integer zeroOne(Item[] items,
                                   Integer totalWeight,
                                   Map<Integer, Integer> valueMemory,
                                   Map<Integer, Set<Integer>> pathMemory){
        //dp
        if(valueMemory.containsKey(totalWeight)){
            return valueMemory.get(totalWeight);
        }
        ArrayList<Integer> available = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            if(items[i].getWeight() <= totalWeight){
                available.add(i);
            }
        }
        if(available.size() == 0){
            valueMemory.put(totalWeight, 0);
            pathMemory.put(totalWeight, new HashSet<>());
            return 0;
        }

        Integer maxValue = -1;
        Integer maxIndex = -1;
        for(Integer ava : available){


            int value = items[ava].getValue() +
                    zeroOne(items, totalWeight - items[ava].getWeight(), valueMemory, pathMemory);
            //run and find
            Set<Integer> path = pathMemory.get(totalWeight - items[ava].getWeight());
            if(path.contains(ava))continue;

            if(value > maxValue){
                maxValue = value;
                maxIndex = ava;
            }
        }

        valueMemory.put(totalWeight, maxValue);

        Set<Integer> newPath = new HashSet<>(pathMemory.get(totalWeight - items[maxIndex].getWeight()));
        newPath.add(maxIndex);
        pathMemory.put(totalWeight, newPath);
        return maxValue;



    }

valueMemory:对于key容量的包最大可装value的价值
pathMemory:记录怎么装

这里思路是先找到一个可被装下的物体(在全部物体中),然后再用剩下的容量作为参数传入该函数。将结果取回后,看一下有没有重复拿取物体。
比较所有这样子可行的装法,找到最大的作为返回值

调度问题

短作业优先,排序,然后贪心

单源最短路径

贝尔曼福特算法,因为它可以计算负权值

全部最短路径

弗洛伊德算法,略了

第四次上机(回溯)

1.0/1 Knapsack Problem. There are 5 items that have a value and weight list below, the knapsack can contain at most 100 Lbs. Solve the problem using back-tracking algorithm and try to draw the tree generated.

2.Solve the 8-Queen problem using back-tracking algorithm.

0-1背包问题

略了,动态规划版改改

八皇后问题

private static void backpack(Set<Pair<Integer, Integer>> available,
                                 Set<Pair<Integer, Integer>> installed,
                                 Integer Queens,
                                 Set<Set<Pair<Integer, Integer>>> solved){
        if(installed.size() == Queens){
            solved.add(installed);
        }

        for(Pair<Integer, Integer> index : available){
            Set<Pair<Integer, Integer>> newInstalled = new HashSet<>();
            Set<Pair<Integer, Integer>> newAvailable = new HashSet<>();

            newInstalled.addAll(installed);
            newInstalled.add(index);

            newAvailable.addAll(available);
            newAvailable.removeIf(new Predicate<Pair<Integer, Integer>>() {
                @Override
                public boolean test(Pair<Integer, Integer> pair) {

                    return pair.i == index.i ||
                            pair.j == index.j ||
                            (pair.i - index.i) == (pair.j - index.j) ||
                            (pair.i - index.i) == (index.j - pair.j);
                }
            });

            backpack(newAvailable, newInstalled, Queens, solved);
        }


    }

available:剩下可放的位置
installed:记录已放的皇后位置
solved:记录已解决的
逐个调用递归

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值