POJ 1852 Ants 簡單的彈性碰撞問題

題目傳送門 點擊這裏
中文大意:
有n只螞蟻在木棍上爬行,每隻螞蟻的速度都是每秒1單位長度,現在給出所有螞蟻初始的位置,但是沒有給出螞蟻的運動方向,如果螞蟻相遇會掉頭反向運動,需要求出所有螞蟻都·掉下木棍的最短時間和最長時間。

解題思路概要
兩個螞蟻相撞之後,其實跟沒有撞的效果是一樣的。相當於還是每個螞蟻在單獨運動。
所以準備了兩個數組,第一個數組存放題目中錄入的數據。
第二個數組的大小是第一個數組的二倍。其中存入的數據除了第一個數組中的數據外,還要有木棍的長度減去第一個數組中的每個數。
相當於說第二個數組中存放的是每個螞蟻到左右兩個端點的距離。
然後用快排對第二個數組進行排序。
其中下標爲num-1的恰好是最短時間,下標爲num*2-1的恰好爲最長的時間。
源代碼及註釋見下

//written by Kingdeguo 2020.4.4
//All rights reversed
#include <stdio.h>
#include <stdlib.h> //to use qsort

//declare out of main function because is the scale of data is a little big
//prevent stack overflow
const int maxn = 1000010;
int Distance[maxn];
int Distance2[maxn*2];

int cmp(const void *a,const void *b)
{
    return *(int *)a-*(int *)b;//If you want to from large to small,write this "return *(int *)b-*(int *)a;"
}

int main()
{
	int casenum=0;
	int length=0, num=0;
	scanf("%d",&casenum);
	int i=0;
	while(casenum){
		scanf("%d %d",&length,&num);

		for(i=0; i<num; ++i){
			scanf("%d",&Distance[i]);

			Distance2[i]=Distance[i];
			Distance2[i+num] = length-Distance[i];
		}
		qsort(Distance2,num*2,sizeof(Distance2[0]),cmp);
		printf("%d %d\n",Distance2[num-1],Distance2[num*2-1]);
		casenum--;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章