查看: 22433| 回复: 45
跳转到指定楼层
上一主题 下一主题
收起左侧

[Coursera]Stanford 算法课 Design and Analysis of Algorithm I 第二期 Week1 加分贴

全局:
讨论在这里:



贴出作业,参与讨论的,来这里求加分,每完成一周有一个学分

下周开始Q&A和加分合一个楼
如果要贴答案的请用白色字体hide一下
单选投票, 共有 78 人参与投票
91.03% (71)
8.97% (7)
您所在的用户组没有投票权限

点评

麻烦大家还是贴PA得分的截图吧。。贴code有违honor code,而且版主也不好加分。。讨论也请注意不要随便贴code  发表于 2012-12-17 08:31

上一篇:[公开课] Stanford Design and Analysis of Algorithm I 第二期 week#1 Q&A
下一篇:Stanford Design and Analysis of Algorithm I 第二期 Week#2 自由讨论
🔗
seekinghelp 2012-6-13 21:06:01 | 只看该作者
全局:
今天做完了Problem Sets和Programming Questions。贴出来共享一下吧。
Problem Sets:Question 1
3-way-Merge Sort : Suppose that instead of dividing in half at each step of Merge Sort, you divide into thirds, sort each third, and finally combine all of them using a three-way merge subroutine. What is the overall running time of this algorithm? (Hint: Note that the merge step can still be implemented in O(n) time.)
Answer:nlog(n)

Question 2
You are given functions f and g such that f(n)=O(g(n)). Is f(n)∗log2(f(n)c)=O(g(n)∗log2(g(n))) ? (Here c is some constant >0. You should assume that f and g are nondecreasing and always bigger than 1.
Answer:True

Question 3
Assume again two (positive) functions f and g such that f(n)=O(g(n)). Is 2f(n)=O(2g(n)) ? (Multiple answers may be correct.)
Answer:Sometimes and Yes if  f(n)≤g(n) for all sufficiently large n

Question 4
k-way-Merge Sort. Suppose you are given k sorted arrays, each with n elements, and you want to combine them into a single array of kn elements. Consider the following approach. Using the merge subroutine taught in lecture, you merge the first 2 arrays, then merge the 3rd given array with this merged version of the first two arrays, and so on until you merge in the final (kth) input array. What is the running time taken by this strategy, as a function of k and n? (Optional: can you think of a faster way to do the k-way merge procedure ?)
Answer:θ(nk^2)

Question 5
Arrange the following functions in increasing order of growth rate (with g(n) following f(n) in your list if and only if f(n)=O(g(n))).
a)(n^2)log(n)
b)2^n
c)2^(2^n)
d)n^(log(n))
e)n^2
Write your 5-letter answer, i.e., the sequence in lower case letters in the space provided. For example, if you feel that the answer is a->b->c->d->e, then type abcde in the space provided without any spaces before / after / in between the string. You can assume that all logarithms are base 2 (though it actually doesn't matter). WARNING: this question has multiple versions, you might see different ones on different attempts!
Answer:eadbc
其中Question 5 中需要排列的几项因人而异。

Programming Questions:
Question 1
Download the text file here. (Right click and save link as)

This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some random order, with no integer repeated.

Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array.
Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures. The numeric answer for the given input file should be typed in the space below.
So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. You can make up to 5 attempts, and we'll use the best one for grading.
(We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.)

[Tip: before submitting, first test the correctness of your program on some small test files or your own devising.]

Answer:2407905288

程序可以参考第一期:Week#1Q&A  Python Java C C++都有。


评分

参与人数 2大米 +40 学分 +1 收起 理由
midfirefly + 20 + 1
paradox + 20 hide, plz!

查看全部评分

回复

使用道具 举报

🔗
EDream 2012-6-14 16:20:08 | 只看该作者
全局:
本帖最后由 EDream 于 2012-6-16 13:50 编辑

update2:今天把problem set完成了。
5道题目答案分别为 nlog(n); True;
Yes if
f(n)≤g(n)
for all sufficiently large and sometimes;
θ
(
n
k2
)
; dcbae

第一次算出的结果和答案有点不一样,debug好久都没看出来,input size小的时候是正确的,一旦变大就出错了...
Update1: 最后没有把结果更新到num数组,刚把code添加了,答案正确。
  1. package Edream_CountInversions;

  2. import java.io.*;

  3. public class Edream_CountInversions {
  4.         
  5.         public static int NUMS_LEN = 200000;
  6.         public static String PATH = "IntegerArray.txt";
  7.         
  8.         public static void main(String args[]) {
  9.                 BufferedReader rd = OpenFileReader();
  10.                 int [] nums = new int[NUMS_LEN];
  11.                 int index = -1;
  12.                 try {
  13.                         while (true) {
  14.                                 String num = rd.readLine();
  15.                                 if (num == null) break;
  16.                                 nums[++index] = Integer.parseInt(num);
  17.                         }
  18.                         rd.close();
  19.                 } catch (IOException ex) {
  20.                         System.out.println("An I/O Error has occured.");
  21.                 }
  22.                 System.out.println(index);
  23.                 System.out.print("The number of Inversions is: ");
  24.                 System.out.println(CountInversions(nums, 0, index));
  25.         }
  26.         
  27.         public static BufferedReader OpenFileReader() {
  28.                 BufferedReader rd = null;
  29.                 try {
  30.                         while (rd == null) {
  31.                                 rd = new BufferedReader(new FileReader(PATH));
  32.                         }
  33.                 } catch (IOException ex) {
  34.                         System.out.println("Can't open that file.");
  35.                 }
  36.                 return rd;
  37.         }
  38.         
  39.         public static long CountInversions(int[] nums, int start, int end) {               
  40.                 int[] tmpArr = new int[NUMS_LEN];
  41.                 return CountInversions(nums, tmpArr, start, end);
  42.         }
  43.         
  44.         private static long CountInversions(int[] num, int[] tmpArr, int start, int end) {
  45.                 long countLeft, countRight, countSplit;
  46.                 int middle = (start + end) / 2;
  47.                 if (start >= end)
  48.                         return 0;               
  49.                 countLeft = CountInversions(num, tmpArr, start, middle);
  50.                 countRight = CountInversions(num, tmpArr, middle+1, end);
  51.                 countSplit = CountSplit(num, tmpArr, start, middle+1, end);
  52.                 return (countLeft + countRight + countSplit);
  53.         }
  54.         
  55.         private static long CountSplit(int[] num, int[] tmpArr, int leftPos,
  56.                         int rightPos, int rightEnd) {
  57.                 int leftEnd = rightPos - 1;
  58.                 int tmpPos = leftPos;
  59.                 int numElem = rightEnd - leftPos + 1;
  60.                 long count = 0;
  61.                
  62.                 while (leftPos <= leftEnd && rightPos <= rightEnd) {
  63.                         if (num[leftPos] <= num[rightPos]) {
  64.                                 tmpArr[tmpPos++] = num[leftPos++];
  65.                         } else {
  66.                                 tmpArr[tmpPos++] = num[rightPos++];
  67.                                 count += leftEnd - leftPos + 1;
  68.                         }
  69.                 }               
  70.                 while (leftPos <= leftEnd) {
  71.                         tmpArr[tmpPos++] = num[leftPos++];
  72.                 }               
  73.                 while (rightPos <= rightEnd) {
  74.                         tmpArr[tmpPos++] = num[rightPos++];
  75.                 }
  76.                
  77.                 for (int i = 0; i < numElem; i++, rightEnd--) {
  78.                         num[rightEnd] = tmpArr[rightEnd];
  79.                 }
  80.                
  81.                 return count;
  82.         }
  83. }
复制代码

回复

使用道具 举报

🔗
twfx1123 2012-6-15 10:14:45 | 只看该作者
全局:
本帖最后由 gy21 于 2012-6-15 10:15 编辑

程序如下,希望保持简洁风格~就加分咯~~~~

import java.io.BufferedReader;
import java.io.FileReader;

public class mergesort {

        long count = 0;
         
        
        public void sort(int[] a, int l, int r){
                if(l<r){
                        int mid = (l+r)/2;
                        sort(a,l,mid);
                        sort(a,mid+1,r);
                        merge(a,l,mid,r);
                }
        }
        
        
        public void merge(int[] a, int l, int mid, int r){
                int [] b = new int[a.length];
                int i = l;
                int j = mid+1;
                int k = 0;
                while(i<=mid && j<=r){
                        if(a < a[j]){
                                b[k++] = a[i++];
                        }
                        else{
                                b[k++] = a[j++];
                                count += mid-i+1;
                        }
                        
                }
                while(i<=mid){
                        b[k++] = a[i++];
                }
                while(j<=r){
                        b[k++] = a[j++];
                }
                for(i=l,k=0;i<=r;i++,k++)
                        a[i] = b[k];

        }
         


          public static void main(String[] args) throws Exception {
                String filename = "/Users/xiaomifeng/Documents/IntegerArray.txt";
                BufferedReader in = new BufferedReader(new FileReader(filename));
                int[] array = new int[100000];
                String data = "";
                int i = 0;
                while ((data = in.readLine()) != null) {
                    array[i++] = Integer.valueOf(data);
                }
                 
                System.out.println(array.length);
                mergesort ms = new mergesort();
                  ms.sort(array, 0, array.length-1);

                  System.out.println(ms.count);
               
            }
        
        
         
        
}

[/i]
回复

使用道具 举报

🔗
DWade 2012-6-15 13:08:32 | 只看该作者
全局:
Question 1
3-way-Merge Sort : Suppose that instead of dividing in half at each step of Merge Sort, you divide into thirds, sort each third, and finally combine all of them using a three-way merge subroutine. What is the overall running time of this algorithm? (Hint: Note that the merge step can still be implemented in O(n) time.)
Your Answer                Score        Explanation
nlog(n)                1.00        That's correct! There is still a logarithmic number of levels, and the overall amount of work at each level is still linear.
Total                1.00 / 1.00       
Question 2
You are given functions f and g such that f(n)=O(g(n)). Is f(n)∗log2(f(n)c)=O(g(n)∗log2(g(n))) ? (Here c is some constant >0. You should assume that f and g are nondecreasing and always bigger than 1.
Your Answer                Score        Explanation
True                1.00        That's correct! Roughly, because the constant c in the exponent is inside a logarithm, it becomes part of the leading constant and gets suppressed by the big-Oh notation.
Total                1.00 / 1.00       
Question 3
Assume again two (positive) functions f and g such that f(n)=O(g(n)). Is 2f(n)=O(2g(n)) ? (Multiple answers may be correct.)
Your Answer                Score        Explanation
Sometimes                0.25       
Always                0.25        What if f(n) = 2n and g(n) = n?
Yes if f(n)≤g(n) for all sufficiently large n                0.25       
Never                0.25        For example, what if f(n)=g(n)?
Total                1.00 / 1.00       
Question 4
k-way-Merge Sort. Suppose you are given k sorted arrays, each with n elements, and you want to combine them into a single array of kn elements. Consider the following approach. Using the merge subroutine taught in lecture, you merge the first 2 arrays, then merge the 3rd given array with this merged version of the first two arrays, and so on until you merge in the final (kth) input array. What is the running time taken by this strategy, as a function of k and n? (Optional: can you think of a faster way to do the k-way merge procedure ?)
Your Answer                Score        Explanation
θ(nk2)                1.00        That's correct! For the upper bound, the merged list size is always O(kn), merging is linear in the size of the larger array, and there are k iterations. For the lower bound, each of the last k/2 merges takes Ω(kn) time.
Total                1.00 / 1.00       
Question 5
Arrange the following functions in increasing order of growth rate (with g(n) following f(n) in your list if and only if f(n)=O(g(n))).

a)n2log(n)
b)2n
c)22n
d)nlog(n)
e)n2

Write your 5-letter answer, i.e., the sequence in lower case letters in the space provided. For example, if you feel that the answer is a->b->c->d->e, then type abcde in the space provided without any spaces before / after / in between the string. You can assume that all logarithms are base 2 (though it actually doesn't matter). WARNING: this question has multiple versions, you might see different ones on different attempts!
Answer for Question 5

Your Answer                Score        Explanation
eadbc                4.00       
Total                4.00 / 4.00
回复

使用道具 举报

🔗
seekinghelp 2012-6-15 22:09:57 | 只看该作者
全局:
视频中的Algorithm for Counting Inversions和Algorithm for Closest Pairs基本与参考书KT中的一致,如果看视频不是很清楚的话可以看书,可惜是扫描版的,看的不是很爽。在其他基本参考书中,counting invetsions 和 closest paris作为习题出现。
回复

使用道具 举报

🔗
steveneo 2012-6-16 02:51:53 | 只看该作者
全局:
本帖最后由 steveneo 于 2012-6-16 03:09 编辑

我的代码第一遍没有得出正确答案,经过n久的调试发现问题,在回帖最后一段贴出问题,请大家帮忙解答一下,谢谢啦~~

首先贴出正确的代码

  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. using namespace std;

  5. double countInversion(vector<double> & vec);
  6. double merge(vector<double> & vec, vector<double> & v1, vector<double> & v2);

  7. int main() {
  8.         ifstream fin("in.txt");
  9.         vector<double> init;
  10.         double temp;
  11.         
  12.         //为什么用这个while循环,vector里最后一个数字会出现两遍
  13.         //while(!fin.eof()) {
  14.         //        fin>>temp;
  15.         //        init.push_back(temp);
  16.         //}

  17.         for(int p = 0; p < 100000; p++) {
  18.                 fin>>temp;
  19.                 init.push_back(temp);
  20.         }

  21.         double dataSize = init.size();
  22.         cout<<dataSize<<endl;

  23.         double x = countInversion(init);
  24.         char str[20];
  25.         sprintf(str,"%.8lf",x);
  26.         printf("%s",str);

  27.         return 0;
  28. }



  29. double countInversion(vector<double> & vec) {
  30.         double n = vec.size();
  31.         if( (n - 1) <  0.0000001 ) return 0;
  32.         
  33.         double result = 0;
  34.         double mid = n / 2;

  35.         vector<double> v1, v2;

  36.         double k = 0;
  37.         while( k < n) {
  38.                 if(k < mid) {
  39.                         v1.push_back(vec[k]);
  40.                         k += 1;
  41.                 } else {
  42.                         v2.push_back(vec[k]);
  43.                         k += 1;
  44.                 }
  45.         }

  46.         double c1 = countInversion(v1);
  47.         double c2 = countInversion(v2);

  48.         vec.clear();
  49.         double c3 = merge(vec, v1, v2);

  50.         result = c1 + c2 + c3;
  51.         return result;
  52. }

  53. double merge(vector<double> & vec, vector<double> & v1, vector<double> & v2) {
  54.         double ans = 0;

  55.         long n1 = v1.size();
  56.         long n2 = v2.size();

  57.         long p1 = 0;
  58.         long p2 = 0;

  59.         double size = n1 + n2;
  60.         for(double k = 0; k < size && p1 < n1 && p2 < n2; k++) {
  61.                 if(v1[p1] <= v2[p2]) {
  62.                         vec.push_back(v1[p1]);
  63.                         p1 += 1;
  64.                 } else {
  65.                         vec.push_back(v2[p2]);
  66.                         p2 += 1;
  67.                         ans += n1 - p1;
  68.                 }
  69.         }

  70.         while(p1 < n1) {
  71.                 vec.push_back(v1[p1]);
  72.                 p1 += 1; }

  73.         while(p2 < n2) {
  74.                 vec.push_back(v2[p2]);
  75.                 p2 += 1;
  76.         }

  77.         return ans;
  78. }
复制代码

然后请问一下我将txt文件里的数据读入vector的时候,用while(!fin.eof()) 循环,会把txt里最后一个数据91901读入两编(vector里第99999和100000个元素都是91901),最后结果错误。
但是当我把while循环改为for(int p = 0; p < 100000; p++)读数据时,一切正常,vector最终大小为100000,最后一个元素是第99999个,大小为91901,最后答案正确。
百思不得其解,求高手指教!!
另外请问怎么设置代码为白色,我在 回复框里显示的白底白字,一按发表颜色就又出来了,囧……



回复

使用道具 举报

🔗
DWade 2012-6-16 15:33:46 | 只看该作者
全局:
  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;

  4. public class Main {

  5.         public static void main(String[] args) throws IOException {
  6.                 BufferedReader bf=new BufferedReader(new FileReader("IntegerArray.txt"));
  7.                 String line;
  8.                 int size=0;
  9.                
  10.                 while((line=bf.readLine())!=null){
  11.                         size++;
  12.                 }
  13.                 int[] a=new int[size];
  14.                 int count=0;
  15.                 bf=new BufferedReader(new FileReader("IntegerArray.txt"));
  16.                 while((line=bf.readLine())!=null){
  17.                         a[count]=Integer.parseInt(line);
  18.                         count++;
  19.                 }
  20.                 double val=mergesort(a, 0, a.length - 1);
  21.                 System.out.println(val);
  22.         }

  23.         public static double mergesort(int[] a, int low, int high) {
  24.                 if (low < high) {
  25.                 int mid = (low + high) / 2;
  26.                 double c1=mergesort(a, low, mid);
  27.                 double c2=mergesort(a, mid + 1, high);
  28.                 double c3=merge(a, low, mid, high);
  29.                 return c1+c2+c3;
  30.                 }
  31.             return 0;
  32.         }

  33.         private static double merge(int[] a, int low, int mid, int high) {
  34.                 double val=0;
  35.                 int[] ret = new int[high - low + 1];
  36.                 int left_p = low;
  37.                 int right_p = mid + 1;
  38.                 int count = 0;
  39.                 while (left_p <= mid && right_p <= high) {
  40.                         if (a[left_p] <= a[right_p]) {
  41.                                 ret[count++] = a[left_p++];
  42.                         } else  {
  43.                         int left= mid-left_p+1;
  44.                         val+=left;
  45.                                 ret[count++] = a[right_p++];
  46.                         }
  47.                 }

  48.                 while (right_p <= high) {
  49.                         ret[count++] = a[right_p++];
  50.                 }
  51.                 while (left_p <= mid) {
  52.                         ret[count++] = a[left_p++];
  53.                 }
  54.                 for(int i=low;i<=high;i++){
  55.                         a[i]=ret[i-low];
  56.                 }
  57.                 return val;
  58.         }
  59. }
复制代码
运行结果
2.407905288E9

和前面的童鞋一样。。。。。。。

回复

使用道具 举报

🔗
yxyxyx 2012-6-16 22:11:57 | 只看该作者
全局:
本帖最后由 yxyxyx 于 2012-6-16 22:16 编辑

#include<iostream>
#include<fstream>
using namespace std;

unsigned int inv = 0;

void countinv(int numbers[], int start, int end, int newnum[]);


int main()
{
        ifstream fin("IntegerArray.txt");

        int numbers[100000];
        int newnum[100000];
        int i = 0;
        int start = 0;
        int end = 99999;
        for(i=0; i < end+1; i++)
        {
                fin >> numbers[i];
                //cout << numbers[i] << endl;
        }
        fin.close();
        //calculate the numbers of inversion
        countinv(numbers, start, end, newnum);
        cout << inv << endl;
        return 0;
}

void countinv(int numbers[], int start, int end, int newnum[])
{
        if(start == end) return;/*if there is only one element then return*/
        int mid = (start+end)/2;
        countinv(numbers, start, mid, newnum);
        countinv(numbers, mid+1, end, newnum);
        /*now the subarrays have been sorted, lets sort arrays in the current level*/
        int left = start;
        int right = mid+1;
        int newp = start;
        while(left <= mid && right <= end)
        {
                if(numbers[left] < numbers[right])
                {
                        newnum[newp] = numbers[left];
                        left++;
                        newp++;
                }
                else
                {
                        newnum[newp] = numbers[right];
                        right++;
                        newp++;
                        inv+=mid-left+1;
                }
        }
        if(left <= mid)
        {
                for(int i = left; i < mid+1; i++)
                {
                        newnum[newp] = numbers[i];
                        newp++;
                }
        }
        else if(right <= end)
        {
                for(int i = right; i < end+1; i++)
                {
                        newnum[newp] = numbers[i];
                        newp++;
                }
        }
        /*finished sorting in newnum, lets put the values back into numbers*/
        for(int i = start; i <= end; i++)
        {
                numbers[i] = newnum[i];
        }
        return;
}

答案为2407905288
回复

使用道具 举报

🔗
yxyxyx 2012-6-16 22:37:21 | 只看该作者
全局:
steveneo 发表于 2012-6-16 02:51
我的代码第一遍没有得出正确答案,经过n久的调试发现问题,在回帖最后一段贴出问题,请大家帮忙解答一下,谢 ...

fin.eof的原因是这样的:
fstream的eof判断标准不是文件的最后一个字符,而是读到文件结束符(0xff)(文件最后一个字符的后面一个字符),所以在读完了最后一个字符之后eof仍然是false,因此会再读一遍,然后才是true。至于为什么再读一遍的时候还是文件最后一个字符,我也不是很清楚,求高手解答~
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表