洛谷【P1104】生日(插入排序版)

题目传送门:https://www.luogu.org/problemnew/show/P1104

题目很简单,我主要是来讲插入排序的。

所谓插入排序,就是从待排序数组不断将数据插入答案数组里。

假设前\(i\)位都排好了,我们要把第\(i+1\)个数字扔进答案数组里。我们先找到答案数组里第一个比这个数字大(或小)的数的位置,把从这个位置开始一直到最后的所有数往后移一位,把要排序的数字放在这个空出来的位置上。重复\(n\)遍就可以把无序的待排序数组排好成答案数组了。

时间复杂度:\(O(n^2)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

int n;

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

struct OIer {
	char s[20];
	int year,month,day,id;

	bool operator<(const OIer &a)const {
		if(year==a.year&&month==a.month&&day==a.day)return id>a.id;
		if(year==a.year&&month==a.month)return day<a.day;
		if(year==a.year)return month<a.month;
		return year<a.year;
	}//重载运算符细节根据题目决定
}O[105],ans[105];

int main() {
	n=read();
	for(int i=1;i<=n;i++) {
		O[i].id=i;
		scanf("%s%d%d%d",O[i].s,&O[i].year,&O[i].month,&O[i].day);
	}
	for(int i=1;i<=n;i++) {
		int pos;
		for(pos=1;pos<i;pos++)
			if(O[i]<ans[pos])break;//pos就是第一个比O[i]的位置。如果不存在这个位置,pos将等于i
		for(int j=i;j>pos;j--)
			ans[j]=ans[j-1];//从pos到i-1的所有数据往后移一位
		ans[pos]=O[i];//把O[i]填进ans[pos]
	}
	for(int i=1;i<=n;i++)
		printf("%s\n",ans[i].s);
	return 0;
}
posted @ 2018-09-14 09:48  AKMer  阅读(282)  评论(0编辑  收藏  举报