[Auxiliary Exercise 1 for Learning Algorithms] Peking University POJ2388: Who's in the Middle

 First put the algorithm topic attached to Mr. Chi Hao's email, so that it will be easy to find in the future.


Attachment: Classification of some topics on Peking University POJ, thanks to Yang Hao for helping to organize. The number is the corresponding question number, and the system can retrieve the corresponding question accordingly.

1. Enumeration: 1753, 2965

2. Greedy: 2109, 2586

3. Minimum spanning tree: 2485, 1258

4. Sorting: 2388

5. In-depth optimization search: 1321, 2251

6. Breadth optimized search: 3278, 1426

7. Simple search techniques and pruning: 2676

8. The knapsack problem: 1837

9. Topological sorting: 1094

10. Shortest path algorithm: 1062, 1125, 2240

11. Huffman tree: 3253

12. Efficient search methods such as hash table and binary search: 2151, 2503

 Hokkaido University POJ2388: Who's in the Middle

——I just finished reading the second chapter of "Programming Pearls" yesterday, which mentioned sorting, so I chose this question as an exercise.

topic

Portal

analyze: 

Use the idea of ​​divide and conquer.

Thinking that the complexity of using quick sort would be lower, I decided to use quick sort to sort the given sequence first, and then output the median.

 code:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

#define swap(a,b){int t=a;a=b;b=t;} 

int a[10005];
int partition(int left,int right){
	int i=left,j=right,t=0;
	int key=a[i];//以最左边点为基准,即创造了一个空位 
	while(i<j){
		while(i<j&&a[j]>=key){
			j--;//向左寻找比key小的数,找到则跳出while循环 
		} 
		if(i<j){
			a[i]=a[j];//a[j]就是那个小于key的值,赋给a[i](左边的坑),使小于key的值放于左边;
		} 
		//接下来从左向右找大于key的值去 
	    while(i<j&&a[i]<=key){
	    	i++;//向右寻找比key大的数,找到则跳出循环 
		}
		if(i<j){
			a[j]=a[i];//把找到的大于key的值赋给a[j](即右边的坑) ,使大于key的值放于右边 
		} 
	}
	//当i==j时,跳出了while循环,此时就剩i=j的这个空位 
	a[i]=key;//最后用key填上那个坑 
	
	return i;
}
void quicksort(int left,int right){
	if(left<right){
		int i=partition(left,right);//划分
	     quicksort(left,i-1);//分别对左右两边进行递归划分
	     quicksort(i+1,right);
	}
}
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
	} 
	quicksort(0,n-1);
//	for(int i=0;i<n;i++){//可以打印排序后的结果
//		cout<<a[i]<<" ";
//	}
//	cout<<endl;
	cout<<a[(n)/2]<<endl;
}



perception 

Ask the teacher to learn the skills of algorithm

——It is still better to do more questions, according to the type, and you will have ideas if you do more.

——Don’t write codes by hand, use computer more often, because many seemingly simple algorithm problems have many restrictions on their boundary conditions, which are extremely error-prone!

My brother gave me two practice references:

Portal 1 

Portal 2

Guess you like

Origin blog.csdn.net/weixin_43594181/article/details/122984709