楼主: midfirefly
跳转到指定楼层
上一主题 下一主题
收起左侧

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

🔗
Nergigante 2012-6-18 23:31:13 | 只看该作者
全局:
本帖最后由 enthalpy_yan 于 2012-6-18 23:45 编辑



fp=open("IntegerArray.txt", "r")
all_lines=fp.readlines()
fp.close()
all_lines = [L.rstrip('\n') for L in all_lines]
all_lines = all_lines[:-1]
input = [int(entry) for entry in all_lines]

def merge(left, right):
    result = []
    count = 0
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left <= right[j]:
            result.append(left)
            i += 1
        elif left > right[j]:
            result.append(right[j])
            count += len(left) + j + 1 - len(result)
            j += 1
    while i < len(left):
        result.append(left)
        i += 1
    while j < len(right):
        result.append(right[j])
        j += 1
    return result, count

def merge_sort(list):
    if len(list) <= 1:
        return [list[0]], 0
    else:
        left = list[:len(list) / 2]
        right = list[len(list) / 2:]
        sL, cL = merge_sort(left)
        sR, cR = merge_sort(right)
        rS, rC = merge(sL, sR)
        return rS, rC + cL + cR

print merge_sort(input)
回复

使用道具 举报

🔗
justin 2012-6-19 13:29:14 | 只看该作者
全局:
yxyxyx 发表于 2012-6-16 22:37
fin.eof的原因是这样的:
fstream的eof判断标准不是文件的最后一个字符,而是读到文件结束符(0xff)(文件 ...

遇到了同样的问题。。。所以算出来的答案比正确答案少1
多谢指点!
回复

使用道具 举报

🔗
justin 2012-6-19 13:33:27 | 只看该作者
全局:
说真的,100000个数0.3s就排完了,不得不让人感叹cs的强大!
回复

使用道具 举报

🔗
sevensin 2012-6-19 15:02:58 | 只看该作者
全局:
用了C++和Python写第一次作业。先写心得再贴代码。总的来说目标如下:想写的代码比较通用,比如适应不同输入的文件大小以及空行的处理;还有就是要用语言的特点;再者程序要简短但是不失可读性,所以我一般用长变量名,压缩行数;最后,就是尽量进行对数据批量操作(当初学Matlab养成的习惯), 可能的话避免for循环。想来在这个位置就不需要用白色了吧。

C++:
1 关于空行的处理,用getline判断string长度是否为零,是则略过该行。
2 使用了C++里面的vector,很好用,建议大家玩一下,自从用了这个,再也不想用int*了。
3 由于MergeSort比较难以实现in-place-operation,所以需要在vector里面大规模复制数据,这点我用for循环做的,估计比较费时了,不知有没有更好的办法。
4 之前有错,错在下标,一要仔细,还有就是先在纸上写写,不要直接敲代码。
5 这个是唯一没有自己检查出来的地方,数据溢出,要用unsigned long或者long long....orz
  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4. #include <sstream>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <vector>
  8. using namespace std;

  9. void copyVector(vector<int> &outVec, vector<int> &inVec, int low, int high) {
  10.         outVec.clear();
  11.         for (int k = low; k <= high; k++) {
  12.                 outVec.push_back(inVec[k]);
  13.         }
  14. }

  15. void mergeSortInv(vector<int> &arr, int low, int high, long long &invCount) {
  16.         if (high - low < 1)        return;
  17.         int pivot = (high + low) / 2;
  18.         mergeSortInv(arr, low, pivot, invCount);
  19.         mergeSortInv(arr, pivot + 1, high, invCount);
  20.         vector<int> temparr;
  21.         copyVector(temparr, arr, low, high);
  22.         int i = 0, j = pivot - low + 1, idx = low, mid = pivot - low;
  23.         while (i <= mid && j <= high - low) {
  24.                 if (temparr[i] > temparr[j]) {
  25.                         arr[idx] = temparr[j];
  26.                         j++;
  27.                         invCount = invCount + mid - i + 1;
  28.                 } else {
  29.                         arr[idx] = temparr[i];
  30.                         i++;
  31.                 }
  32.                 idx++;
  33.         }
  34.         while (i <= mid) {
  35.                 arr[idx] = temparr[i];
  36.                 idx++;
  37.                 i++;
  38.         }
  39.         while (j <= high - low) {
  40.                 arr[idx] = temparr[j];
  41.                 idx++;
  42.                 j++;
  43.         }
  44.         return;
  45. }

  46. int main() {
  47.         string InputFileName = "IntegerArray.txt";
  48.         ifstream infile(InputFileName.c_str());
  49.         if (!infile.is_open()) {
  50.                 cerr << "Error with file opening";
  51.                 exit(1);
  52.         }
  53.         vector<int> IntArray, NewArray;
  54.         string templine;
  55.         while (!infile.eof()) {
  56.                 getline(infile, templine);
  57.                 if (templine.size() == 0)
  58.                         continue;
  59.                 IntArray.push_back(std::atoi(templine.c_str()));
  60.         }
  61.         infile.close();
  62.         cout << IntArray.size() << " numbers acquired." << endl;
  63.         NewArray = IntArray;
  64.         long long InvCount = 0;
  65.         mergeSortInv(NewArray, 0, NewArray.size() - 1, InvCount);
  66.         cout <<"Total # of inversion pairs is:"<< InvCount;
  67.         return 0;
  68. }
复制代码
Python:
最近才开始正式的用python,之前的都是小打小闹,
1 我的def的函数要返回两个值,一个是sorted list,一个是inv #。 查了一下,用tuple做的。
2 利用list的方法,最后写出来的东西相当简洁,核心函数15行,总共不到20来行,我自己也惊奇了一下。
  1. def mergeSortInv(toSort,ctInv):
  2.         if len(toSort)<=1: return (toSort, ctInv)
  3.         pivot = len(toSort)/2
  4.         (left, ctInv) = mergeSortInv(toSort[:pivot],ctInv)
  5.         (right, ctInv) = mergeSortInv(toSort[pivot:],ctInv)
  6.         result=[]
  7.         while (  left ) and ( right):
  8.                 if left[0]>right[0]:
  9.                         ctInv=ctInv+len(left)
  10.                         result.append(right.pop(0))
  11.                 else:
  12.                         result.append(left.pop(0))
  13.         result.extend(left)
  14.         result.extend(right)
  15.         return (result, ctInv)

  16. InputFileName = "IntegerArray.txt"
  17. FileIn = open(InputFileName, 'r')
  18. IntArray = map(int, FileIn.readlines())
  19. FileIn.close()
  20. print "Read " + str(len(IntArray)) + " integers from file: " + InputFileName
  21. (res, invCount)=mergeSortInv(IntArray,0)
  22. print "The # of inversion paris is \t %d" %(invCount)
复制代码
回复

使用道具 举报

🔗
lichcat 2012-6-20 01:56:54 | 只看该作者
全局:
本帖最后由 lichcat 于 2012-6-20 02:35 编辑

我也来贴一段C的好了,其实用不大习惯C,写的很丑陋主要是因为我不知道MergeSort怎么原地排序,所以就会有众多的临时数据存储,
之前看endless 同学的C程序存放数据的数组,不论是原始数据,还是中间临时数组,都是函数内局部定义,即存在栈上
我习惯是大数据放在堆上,在栈上用参数传递大数组总觉得怪怪的,
这样一来我就写成下面这样了,结果倒是没问题,就是指针操作烦点


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #define SIZE 100000


  5. typedef struct{
  6.         int* list;
  7.         unsigned long int num;
  8. }inversion;


  9. inversion* count_split_inversions(inversion* left,int left_len,inversion* right, int right_len){
  10.         int i,j,k,inversions;
  11.         i=j=k=inversions=0;
  12.         inversion* split_inversion=(inversion*)malloc(sizeof(inversion));
  13.         int* merge_array=(int*)malloc((left_len+right_len)*sizeof(int));


  14.         while(i<left_len && j<right_len){
  15.                 if(*(left->list+i)<=*(right->list+j)){
  16.                         *(merge_array+k)=*(left->list+i);
  17.                         i++;
  18.                         k++;
  19.                 }else{
  20.                         *(merge_array+k)=*(right->list+j);
  21.                         j++;
  22.                         k++;
  23.                         inversions+=(left_len-i);
  24.                 }
  25.         }
  26.         while(k<(left_len+right_len)){
  27.                 if(j==right_len){
  28.                         *(merge_array+k)=*(left->list+i);
  29.                         i++;
  30.                         k++;
  31.                 }else if (i==left_len){
  32.                         *(merge_array+k)=*(right->list+j);
  33.                         j++;
  34.                         k++;
  35.                 }
  36.         }
  37.         assert(i==left_len);
  38.         assert(j==right_len);
  39.         split_inversion->list=merge_array;
  40.         split_inversion->num=inversions;
  41.         return split_inversion;
  42. }


  43. inversion* count_inversions(inversion* in_array,int begin, int end){
  44.         assert(begin+1<=end);
  45.         inversion *merge_result=(inversion*)malloc(sizeof(inversion));
  46.         inversion *left_array,*right_array;
  47.         int first,second;
  48.         if(begin+1==end){
  49.                 merge_result->list=(int*)malloc(sizeof(int));
  50.                 *(merge_result->list)=*(in_array->list+begin);
  51.                 merge_result->num=0;
  52.                 return merge_result;
  53.         }else if(begin+2==end){
  54.                 merge_result->list=(int*)malloc(sizeof(int)*2);
  55.                 first=*(in_array->list+begin);
  56.                 second=*(in_array->list+begin+1);
  57.                 *(merge_result->list)=(first<=second)?first:second;
  58.                 *(merge_result->list+1)=(first<=second)?second:first;
  59.                 merge_result->num=(first<=second)?0:1;
  60.                 return merge_result;
  61.         }


  62.         left_array=count_inversions(in_array,begin,(begin+end)/2);
  63.         right_array=count_inversions(in_array,(begin+end)/2,end);
  64.         merge_result= count_split_inversions(left_array,(begin+end)/2-begin,right_array,end-(begin+end)/2);
  65.         merge_result->num+=(left_array->num+right_array->num);
  66.         free(left_array->list);
  67.         free(left_array);
  68.         free(right_array->list);
  69.         free(right_array);


  70.         return merge_result;


  71. }


  72. int main(){
  73.         int count=0,i;
  74.         inversion* result_array;
  75.         inversion* in_array=(inversion*)malloc(sizeof(inversion));
  76.         in_array->list=(int*)malloc(SIZE*sizeof(int));
  77.         while(1==scanf("%d",&(in_array->list[count])))
  78.                 count++;
  79.         result_array=count_inversions(in_array,0,count);
  80.         printf("%lu\n",result_array->num);


  81.         return 0;
  82. }
复制代码

最后贴一下作业截图







评分

参与人数 1大米 +10 学分 +1 收起 理由
midfirefly + 10 + 1 截屏主意不错

查看全部评分

回复

使用道具 举报

🔗
justin 2012-6-20 22:54:28 | 只看该作者
全局:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#define N 100000

long long int inv = 0;

using namespace std;

void m_sort(int *, long int, long int);
void print(int *a);

//归并算法的入口
void merge_sort(int *a, long int n)
{
    m_sort(a, 0, n-1);
}

//将a[s...m]和a[m+1...t]两个有序数组归并为有序数组a[s...t]
void merge(int *a, long int s, long int m, long int t)
{
    int *b = new int[t-s+1];
    if(b == NULL) cout << "overflow!" << endl;
    int i = s, j = m+1, k = 0;
    while(i <= m && j <= t)
    {
        if(a[i] > a[j])
        {
            b[k++] = a[j++];
            inv += (m-i+1);
        }
        else
            b[k++] = a[i++];
    }
    while(i <= m)
        b[k++] = a[i++];
    while(j <= t)
        b[k++] = a[j++];
    //将b中数组拷回a中
    for(i = s, k = 0; i <= t;)
        a[i++] = b[k++];
    delete []b;
}

//将a[s...t]调整为有序数组
void m_sort(int *a, long int s, long int t)
{
    if(s == t)
        return;
    int m = (s+t)/2;
    m_sort(a, s, m);
    m_sort(a, m+1, t);
    merge(a, s, m, t);
}

void print(int *a)
{
    for(int i = 0; i < N; i++)
        cout << "  " << a[i];
    cout << endl;
}

int main()
{
    ifstream fin("IntegerArray.txt");
    int *a = new int[N];
    if(a == NULL) cout << "overflow!" << endl;
    char num[30];
    long int i = 0;
    fin >> num;
    while(!fin.eof())
    {
        a[i++] = atoi(num);
        fin >> num;
    }
    if(i != N)
        cout << "number is not N!" << endl;
    merge_sort(a, N);
    cout << "inv: " << inv << endl;
    delete []a;
    return 0;
}


回复

使用道具 举报

🔗
justin 2012-6-20 23:00:20 | 只看该作者
全局:
问一下,求加分是要贴出程序代码还是作业截图?
回复

使用道具 举报

🔗
 楼主| midfirefly 2012-6-20 23:02:36 | 只看该作者
全局:
justin 发表于 2012-6-20 23:00
问一下,求加分是要贴出程序代码还是作业截图?

都上吧,程序为主
回复

使用道具 举报

🔗
 楼主| midfirefly 2012-6-20 23:02:37 | 只看该作者
全局:
justin 发表于 2012-6-20 23:00
问一下,求加分是要贴出程序代码还是作业截图?

都上吧,程序为主
回复

使用道具 举报

🔗
shidaohang 2012-6-22 09:25:00 | 只看该作者
全局:
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<malloc.h>

  4. const char INFILE[]="IntegerArray.txt";
  5.        
  6. long RTN_LNUM()
  7. {
  8.         FILE*fp = fopen(INFILE,"r");
  9.         long LNUM=0;
  10.         char ch[100];
  11.        
  12.         while (fgets(ch,100,fp))
  13.                 LNUM++;

  14.         fclose(fp);
  15.         return LNUM;
  16. }

  17. long* FETCH_DATA()
  18. {
  19.         long LinNum=RTN_LNUM();                //        Scan the file and return the line number
  20.         FILE*fp = fopen(INFILE,"r");
  21.         long* data;                        //        Store the input data
  22.         char ch[100];
  23.         long i=0;

  24.         data = (long*)calloc(LinNum,sizeof(long));

  25.         for (i=0; i<LinNum; i++)        {
  26.                 fgets(ch,100,fp);
  27.                 data[i]=atoi(ch);
  28.         }
  29.         fclose(fp);
  30.         return data;
  31. }

  32. long CountSplitInv(long* data, long p, long q)       
  33. {
  34.         long *left,*right;
  35.         long i,j,k,r,z;

  36.         z=0;                        //        z is the returned value of inversion numbers
  37.         r=(p+q)/2+1;        //        r is the place where the second array starts

  38.         left = (long*)calloc(r-p+1,sizeof(long));
  39.         right = (long*)calloc(q-r+2,sizeof(long));

  40.         for (k=0; k<r-p; k++)
  41.                 left[k]=data[p+k];
  42.         left[r-p]=1000001;

  43.         for (k=0; k<q-r+1; k++)
  44.                 right[k]=data[r+k];
  45.         right[q-r+1]=1000001;

  46.         i=0; j=0;                //        init the two arrays
  47.         for (k=p; k<q+1; k++)        {
  48.                 if (left[i]<right[j])
  49.                         data[k]=left[i++];
  50.                 else        {
  51.                         data[k]=right[j++];
  52.                         z = z+(r-p-i);
  53.                 }
  54.         }
  55.         return z;
  56. }

  57. long SortAndCount(long* data, long p, long q)
  58. {
  59.         long x,y,z;
  60.         long i;
  61.         if (p==q)
  62.                 return 0;
  63.         else        {
  64.                 x = SortAndCount(data,p,(p+q)/2);
  65.                 y = SortAndCount(data,(p+q)/2+1,q);
  66.                 z = CountSplitInv(data,p,q);
  67.                 return x+y+z;
  68.         }
  69. }

  70. void main()
  71. {
  72.         long * data = FETCH_DATA();
  73.         printf("InvNum = %ld\n",SortAndCount(data,0,RTN_LNUM()-1));
  74. }
复制代码
回复

使用道具 举报

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

本版积分规则

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