Stanford Algorithms: Design and Analysis, Part 2[week 1]

Problem Set-1

Stanford Algorithms: Design and Analysis, Part 2[week 1]_第1张图片 Stanford Algorithms: Design and Analysis, Part 2[week 1]_第2张图片 Stanford Algorithms: Design and Analysis, Part 2[week 1]_第3张图片 Stanford Algorithms: Design and Analysis, Part 2[week 1]_第4张图片 Stanford Algorithms: Design and Analysis, Part 2[week 1]_第5张图片

Programming Assignment-1


Question 1

In this programming problem and the next you'll code up the greedy algorithms from lecture for minimizing the weighted sum of completion times.. Download the text file here. This file describes a set of jobs with positive and integral weights and lengths. It has the format
[number_of_jobs]
[job_1_weight] [job_1_length]
[job_2_weight] [job_2_length]
...
For example, the third line of the file is "74 59", indicating that the second job has weight 74 and length 59. You should NOT assume that edge weights or lengths are distinct.


Your task in this problem is to run the greedy algorithm that schedules jobs in decreasing order of the difference (weight - length). Recall from lecture that this algorithm is not always optimal. IMPORTANT: if two jobs have equal difference (weight - length), you should schedule the job with higher weight first. Beware: if you break ties in a different way, you are likely to get the wrong answer. You should report the sum of weighted completion times of the resulting schedule --- a positive integer --- in the box below.


ADVICE: If you get the wrong answer, try out some small test cases to debug your algorithm (and post your test cases to the discussion forum)!

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.PriorityQueue;


public class PS1Q1 {
	static class Job implements Comparable<Job>{
		int weight;
		int length;
		public int val(){
			return weight-length;
		}
		public Job(int w, int l){
			weight = w; length = l;
		}
		@Override
		public int compareTo(Job arg0) {
			final int BEFORE = 1;
			final int EQUAL = 0;
			final int AFTER = -1;
			// TODO Auto-generated method stub
			if (this.val()==arg0.val()){
				return(this.weight>arg0.weight?(BEFORE):(AFTER));
			}
			return(this.val()>arg0.val()?(BEFORE):(AFTER));			
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {

			ArrayList<Job> l = new ArrayList<Job>();
			FileInputStream fstream = new FileInputStream("jobs.txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String str;
			str=br.readLine();

			int numJobs = Integer.parseInt(str);
			while ((str=br.readLine())!= null){
				String s[] = str.split(" ");
				l.add(new PS1Q1.Job(Integer.parseInt(s[0]),Integer.parseInt(s[1])));		  
			}
			Collections.sort(l);
			Collections.reverse(l);
			int time = 0;
			double weight = 0;
			for(Job j : l){
				weight += j.weight*(time+j.length);
				time += j.length;				
			}
			System.out.println("the final weighth = "+weight);

		} catch ( IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

Question 2

For this problem, use the same data set as in the previous problem. Your task now is to run the greedy algorithm that schedules jobs (optimally) in decreasing order of the ratio (weight/length). In this algorithm, it does not matter how you break ties. You should report the sum of weighted completion times of the resulting schedule --- a positive integer --- in the box below.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.PriorityQueue;


public class PS1Q2 {
	static class Job implements Comparable<Job>{
		int weight;
		int length;
		public double val(){
			return (double)weight/(double)length;
		}
		public Job(int w, int l){
			weight = w; length = l;
		}
		@Override
		public int compareTo(Job arg0) {
			final int BEFORE = 1;
			final int EQUAL = 0;
			final int AFTER = -1;
			// TODO Auto-generated method stub
			if (this.val()==arg0.val()){
				return(this.weight>arg0.weight?(BEFORE):(AFTER));
			}
			return(this.val()>arg0.val()?(BEFORE):(AFTER));			
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {

			ArrayList<Job> l = new ArrayList<Job>();
			FileInputStream fstream = new FileInputStream("jobs.txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String str;
			str=br.readLine();

			int numJobs = Integer.parseInt(str);
			while ((str=br.readLine())!= null){
				String s[] = str.split(" ");
				l.add(new PS1Q2.Job(Integer.parseInt(s[0]),Integer.parseInt(s[1])));		  
			}
			Collections.sort(l);
			Collections.reverse(l);
			int time = 0;
			double weight = 0;
			for(Job j : l){
				weight += j.weight*(time+j.length);
				time += j.length;				
			}
			System.out.println("the final weighth = "+weight);

		} catch ( IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Question 3

In this programming problem you'll code up Prim's minimum spanning tree algorithm. Download the text file here. This file describes an undirected graph with integer edge costs. It has the format
[number_of_nodes] [number_of_edges]
[one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost]
[one_node_of_edge_2] [other_node_of_edge_2] [edge_2_cost]
...
For example, the third line of the file is "2 3 -8874", indicating that there is an edge connecting vertex #2 and vertex #3 that has cost -8874. You should NOT assume that edge costs are positive, nor should you assume that they are distinct.


Your task is to run Prim's minimum spanning tree algorithm on this graph. You should report the overall cost of a minimum spanning tree --- an integer, which may or may not be negative --- in the box below.


IMPLEMENTATION NOTES: This graph is small enough that the straightforward O(mn) time implementation of Prim's algorithm should work fine. OPTIONAL: For those of you seeking an additional challenge, try implementing a heap-based version. The simpler approach, which should already give you a healthy speed-up, is to maintain relevant edges in a heap (with keys = edge costs). The superior approach stores the unprocessed vertices in the heap, as described in lecture. Note this requires a heap that supports deletions, and you'll probably need to maintain some kind of mapping between vertices and their positions in the heap.


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;


public class PS1Q3 {
	static int[][] graph;
	static int numNodes;
	static int[] tree;//it has just edges tree[i] contains j if (i,j) is in tree. This array is NOT symmetric. init to -1
	/*
	 * implements slow O(mn) algo default one
	 */
	public static void primsSlow(){
		int weight = 0;
		boolean[] status = new boolean[numNodes];
		for (boolean i : status)
			i = false;
		status[0] = true;

		int minw = Integer.MAX_VALUE;
		int mini =0 ;
		int minj = 0;
		while(!isComplete(status)){
			for(int i =0;i<numNodes;i++){
				if (status[i]) continue;
				//find in graph an edge with (i,j) where j=true and trace minimum
				for(int j =0;j<numNodes;j++){
					if (!status[j]) continue;
					if (minw > graph[i][j]){
						minw = graph[i][j];
						mini=i;//new node
						minj=j;//old node
					}					
				}
			}
			status[mini] = true;
			tree[minj] = mini;
			weight += graph[mini][minj];
			minw = Integer.MAX_VALUE;
		}
		System.out.println("weight "+weight);

	}

	public static boolean isComplete(boolean[] status){
		for (boolean b : status){
			if (!b) return false;
		}
		return true;

	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			FileInputStream f = new FileInputStream("edges.txt");
			DataInputStream d = new DataInputStream(f);
			BufferedReader b = new BufferedReader(new InputStreamReader(f));
			numNodes = Integer.parseInt(b.readLine().split(" ")[0]);
			graph = new int[numNodes][numNodes];
			for (int i =0;i<numNodes;i++)
				for(int j=0; j < numNodes; j++)
					graph[i][j] =Integer.MAX_VALUE;
			String str;
			while((str=b.readLine())!=null){
				int i = Integer.parseInt(str.split(" ")[0])-1;
				int j = Integer.parseInt(str.split(" ")[1])-1;
				graph[i][j] = Integer.parseInt(str.split(" ")[2]);
				graph[j][i] = Integer.parseInt(str.split(" ")[2]);
			}
			tree = new int[numNodes];
			for (int i : tree)
				i=-1;
			primsSlow();
		} catch (NumberFormatException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}



你可能感兴趣的:(算法,图论,贪心,斯坦福)