-
-
Save mmanzhos/0fff2e4a999487278bf0d883123ec561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mmanzhos; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int N = in.nextInt(); | |
int[] ar = new int[N]; | |
for (int i = 0; i < N; i++) { | |
ar[i] = in.nextInt(); | |
} | |
Arrays.sort(ar); | |
/* | |
6 | |
1 3 6 1 3 5 | |
4 | |
1 1 | |
2 | |
2 2 2 | |
3 | |
3 3 3 3 | |
4 | |
4 4 4 4 4 | |
5 | |
*/ | |
int agreed = 0; | |
List<Integer> latents = new ArrayList<>(); | |
int lastLatent = -1; | |
for (int i = 0; i < N; i++) { | |
if (lastLatent != -1 && ar[lastLatent] == ar[i]) continue; | |
if (ar[i] <= agreed) { | |
agreed++; | |
} else { | |
int missing = ar[i] - agreed; | |
int missingSatisfies = 0; | |
for (int j = i + 1; j < N && j <= i + missing; j++) { | |
if (ar[i] == ar[j]) | |
missingSatisfies++; | |
} | |
if (missing == missingSatisfies) { | |
agreed += missing + 1; | |
i = i + missing; | |
} else { | |
latents.add(i); | |
lastLatent = i; | |
} | |
} | |
} | |
//System.out.println("Agreed now: " + agreed); | |
while (!latents.isEmpty()) { | |
int atLeastOneWasRemoved = 0; | |
for (int i = 0; i < latents.size(); i++) { | |
int index = latents.get(i); | |
if (ar[index] <= agreed) { | |
agreed++; | |
latents.remove(i); | |
atLeastOneWasRemoved++; | |
} else { | |
int missing = ar[index] - agreed; | |
int missingSatisfies = 0; | |
for (int j = index + 1; j < N && j <= index + missing; j++) { | |
if (ar[index] == ar[j]) | |
missingSatisfies++; | |
} | |
if (missing == missingSatisfies) { | |
agreed++; | |
latents.remove(i); | |
atLeastOneWasRemoved++; | |
} | |
} | |
} | |
if (atLeastOneWasRemoved == 0) { | |
break; | |
} | |
} | |
System.out.println(agreed); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment