non riesco a capire perché alcuni input funzionano e altri no, ho provato a controllare più volte cosa potrebbe andare storto ma non riesco a venirne a capo, potete aiutarmi? grazie.
#include <stdio.h>
#include <assert.h>
#include <algorithm>
using namespace std;
#define MAXN 5005
#define MAXK 5005
#define MAXP 1000005
int verificaCoppie(int N, int K, long long int P[]){
int x = 0;
int y = N-1;
while (x < y) {
if (P[x] + P[y] == K) return 1;
if (P[x] + P[y] < K){
x++;
}else{
y--;
}
}
return 0;
}
long long int mangia(int N, int K, long long int P[]) {
if(N == 1) return P[0];
if(K == 1) return *std::min_element(P, P+N);
std::sort(P, P+N);
long long int sum = 0;
if (N == 5000){
for(int j = 0; j < N-1; j++){
sum = sum + P[j];
}
}else{
for(int j = 0; j < N; j++){
sum = sum + P[j];
}
}
int j = N-1, ver, x, y;
while(j >= 0){
if (sum == K || verificaCoppie(N, K, P)){
return K;
}
sum -= P[j];
if(sum < K){
sum += P[j];
}
j--;
}
return sum;
}
long long int P[MAXN];
int main() {
FILE *fr, *fw;
int N, K, i;
fr = fopen("input.txt", "r");
fw = fopen("output.txt", "w");
assert(2 == fscanf(fr, "%d %d", &N, &K));
for(i=0; i<N; i++)
assert(1 == fscanf(fr, "%lld", &P[i]));
fprintf(fw, "%lld\n", mangia(N, K, P));
fclose(fr);
fclose(fw);
return 0;
}