排序加贪心,看了一圈评论区和题解,我这个应该是唯一正确的,评论区里举的其他楼主的解法不能pass的反例,我这个都可以pass。
解法是参考@aglangyue的,但参考的解法也有bug,我这里fix了。大家放心享用!
import java.io.*; import java.util.*; public class Main { private static int read(StreamTokenizer st) throws IOException{ st.nextToken(); return (int) st.nval; } public static void main(String[] args) throws IOException{ StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); //读取N int N = read(st); //读取数组 int[] arr = new int[N]; for(int i=0; i<N; i++){ arr[i] = read(st); } //数组排序 Arrays.sort(arr); //贪心 int pre=-1, size=0, cnt=0; int idx = 0; while(idx<N){ if(size==0){ pre = arr[idx++]; size=1; }else if(size==1){ int gap=arr[idx]-pre; if(gap>10 && gap<=20){ cnt++; size=0; idx++; }else if(gap>20){ cnt += 2; size=1; pre = arr[idx++]; }else{ pre = arr[idx++]; size = 2; } }else{ int gap=arr[idx]-pre; if(gap>10){ cnt++; pre = arr[idx++]; size=1; }else{ size=0; idx++; } } } if(size==1){ cnt +=2; }else if(size==2){ cnt +=1; } System.out.println(cnt); } }