Flatland是一個有n個城市的國家,當中m個城市有太空站(space stations)。
所有城市被由0~n-1編號為C0~Cn-1,
每個Ci和Ci+1之間會有一條雙向的1公里長的道路。
對每個城市來說,我們可以知道其到最近的太空站的距離,
試求這些距離當中最大的值。
(如果自己這個城市有太空站的話對這個城市最近的太空站距離即為0)
輸入:
第一行輸入n, m(以空格隔開)
第二行包含m個數字代表那個編號的城市擁有太空站,
這些數字是未經排列且不重複的。
限制為1<=n<=10的5次方,且1<=m<=n。
輸出:
印出當一個太空人在其中一個城市時,
需要到達最近的太空站的最大可能必須旅行的距離。
解題:
請注意m的輸入是未排序的!!!
解決這點以後,解題應該不難。
我們同樣利用qsort進行事先排序,這裡不再贅述。
當n == m時,表示每個城市都有太空站,故max=0,
就直接省去後續了。
排序後考慮對某個城市的最小距離,
分為2種:
1. 0 -> c[0]和c[m-1]-> n,這兩個的最小距離是兩者相減。
2. c[i]和c[i-1],這兩個要取中間的一個城市並算最小距離,
故將兩者相減除以2。
因為要找這一群最小距離當中的最大值,
故取靠近正中間或剛好正中間的城市。
不斷比較並保留較大值,最後即可印出結果。
Code:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int compare(const void *arg1, const void *arg2){
return (*(int *)arg1 - *(int *)arg2);
}
int main(){
int n;
int m;
scanf("%d %d",&n,&m);
if(n == m)
printf("0");
else{
int *c = malloc(sizeof(int) * m);
int max = 0, temp = 0;
for(int i = 0; i < m; i++){
scanf("%d",&c[i]);
}
qsort((void *)c, m, sizeof(int), compare);
max = c[0];
for(int i = 1; i < m; i++){
temp = (c[i]-c[i-1])/2;
max = (max > temp)? max : temp;
}
temp = n-1 - c[m-1];
max = (max > temp)? max : temp;
printf("%d", max);
}
return 0;
}
沒有留言:
張貼留言