Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

折腾了一天,RE到崩溃,又莫名奇妙的AC了,想不明白,如鲠在喉,劳驾大牛给看看为什么。。。

Posted by TurnAround at 2010-07-07 22:32:05 on Problem 2299
RE的代码(AC的代码在后面):
#include <cstdio>
#include <cstring>

const int size = 600000;
int data[size+1] = {0};
int n;
long long num = 0;

void mergeSort(int left, int right)
{
	if (left >= right) {
		return;
	}
	
	int middle = (left+right)/2;	
	mergeSort(left, middle);
	mergeSort(middle+1, right);
	
	int buf[size+1] = {0};
	int i = left;
	int j = middle+1;
	int id = 1;
		
	while (i<=middle && j<=right) {
		if (data[i] < data[j]) {
			buf[id++] = data[i++];
			num += (j-(middle+1));	
		} else {
			buf[id++] = data[j++];
		}
	}

	while (i <= middle) {
		buf[id++] = data[i++];
		num += (j-(middle+1));	
	}
	while (j <= right) {
		buf[id++] = data[j++];
	}

	i = 1;
	j = left;
	for (; i<id; i++, j++) {
		data[j] = buf[i];	
	}
}

int main()
{
	while (scanf("%d", &n)) {
		if (n == 0) {
			break;
		}
		memset(data, 0, sizeof(data));
		for (int i=1; i<=n; i++) {
			scanf("%d", &data[i]);
		}
		num = 0;
		mergeSort(1, n);
		printf("%lld\n", num);
	}	

	return 0;
}

/***************************************/
AC的代码:就是把mergeSort里的buf数据声明为全局的,其他没变。
#include <cstdio>
#include <cstring>

const int size = 600000;
int data[size+1] = {0};
/*把buf的声明放在这里了,其他没变*/
int buf[size+1] = {0};
int n;
long long num = 0;

void mergeSort(int left, int right)
{
	if (left >= right) {
		return;
	}
	
	int middle = (left+right)/2;	
	mergeSort(left, middle);
	mergeSort(middle+1, right);
	
	int i = left;
	int j = middle+1;
	int id = 1;
		
	while (i<=middle && j<=right) {
		if (data[i] < data[j]) {
			buf[id++] = data[i++];
			num += (j-(middle+1));	
		} else {
			buf[id++] = data[j++];
		}
	}

	while (i <= middle) {
		buf[id++] = data[i++];
		num += (j-(middle+1));	
	}
	while (j <= right) {
		buf[id++] = data[j++];
	}

	i = 1;
	j = left;
	for (; i<id; i++, j++) {
		data[j] = buf[i];	
	}
}

int main()
{
	while (scanf("%d", &n)) {
		if (n == 0) {
			break;
		}
		memset(data, 0, sizeof(data));
		for (int i=1; i<=n; i++) {
			scanf("%d", &data[i]);
		}
		num = 0;
		mergeSort(1, n);
		printf("%lld\n", num);
	}	

	return 0;
}


/*************************************/
没想明白为什么?大牛给解释一下,感激不尽!!!

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator