Stanford公开课之算法:设计与分析——(第一周) Programming Question-1

这是一个Stanford大学算法课程的编程挑战,要求计算1到100,000之间无重复整数的逆序对数量。由于数组规模巨大,需要使用快速的分治算法来解决。学生可以使用任何编程语言,提交最终的数值答案。" 20131387,938416,Hadoop面试关键知识点解析,"['Hadoop', '面试准备', '分布式系统', 'Linux', '数据存储']
摘要由CSDN通过智能技术生成

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 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.)

#include"stdio.h"
#include"math.h"
#include <stdlib.h>
#define MAX_INT 1000000;
#define NUM 100000
long mergeT(int *a,int p,int q,int r)
{
	int n1 = q-p+1;
	int n2 = r-q;
	int* L = new int[n1+1];
	int* R = new int[n2+1];

	for(int i=0;i<n1;i++)
		L[i] = a[p+i];
	
	for(int j=0;j<n2;j++)
		R[j] = a[q+j+1];
	
	L[n1] = MAX_INT;
	R[n2] = MAX_INT;

	i = 0;
	j = 0;
	long count = 0;
	
	for(int k=p;k<r+1;k++)
	{
		if(L[i]<=R[j])
		{
			a[k] = L[i];
			i++;
		}
		else
		{
			count += (long) (n1-i);
			a[k] = R[j];
			j++;
		}
	}
	return count;
}
long merge(int *a,int p, int r)
{
	//printf("合并排序开始:\n");
	int q =0;
	if(p==r)
		return 0;
	else if(p<r)
	{
		q = (int)floor((p+r)/2);
		long left = merge(a,p,q);
		long right = merge(a,q+1,r);
		long cross = mergeT(a,p,q,r);
		return left+right+cross;
	}
	return 0;
}
void show(int *a,int n)
{
	for(int i=0;i<n;i++)
	{
		printf("%d ",a[i]);
	}
	printf("\n");
}
void readFromTxt(int *b)
{
	FILE *fp;
	char buf[7];
	
	int ct = 0;
	fp = fopen("c:\\IntegerArray.txt","r");

	if(fp==NULL)
	{
		perror("fail to read");
		exit(1);
	}

	while(fgets(buf,NUM,fp)!=NULL)
	{
		b[ct++]=strtol(buf,NULL,0);
	}
	printf("一共%d条记录\n",ct);
}
void main()
{
	int b[NUM];
	for(int i=0;i<NUM;i++)
		b[i] = 0;
	readFromTxt(b);
	long count = merge(b,0,NUM-1);
	printf("inversion的数目是:%lu.\n",count);
}
运行结果:

如果发现有什么问题,欢迎留言,多多探讨!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值