题解 | #分苹果#

分苹果

http://www.nowcoder.com/practice/a174820de48147d489f64103af152709

include <math.h>

void findA(int *a, int temp, int index, int average, int n){

int i;
if(temp == (-2)){
    for(i = index+1; i< n ;){
        if(a[i] <= average){
            i++;
            continue;
        }
        else if( a[i] > average ){
            a[i]-=2;
            temp = 0;
            return;
        }
    }
}
else if(temp == (2)){
    for(i = index+1; i< n ;){
        if(a[i] >= average){
            i++;
            continue;
        }
        else if( a[i] < average ){
            a[i]+=2;
            temp = 0;
            return;
        }
    }
}

}

int greedyAlg(int *a, int average, int n){
int count=0;
int temp = 0;
int i = 0;
for( ; i<n ; ){
if(a[i]>average){
a[i]-=2;
temp = 2;
}
else if(a[i]<average){
a[i]+=2;
temp = -2;
}
else{
i++;
continue;
}
// printf("\ntemp = %d a[%d] = %d", temp, i, a[i]);
findA(a, temp, i, average, n);
count++;
}

return count;

}

int main(){
int n;
int *a;
int sum=0, i=0, count=0;
int average;

scanf("%d",&n);
a = (int)malloc(n*sizeof(int));
while(i != n){
    scanf("%d", a+i);
    sum += a[i];
    i++;
}
                 // printf("%d\n", sum%n);
if((sum % n) != 0){
    printf("-1"); 
    return 0;
}
average = sum/n;

for(i=0; i<n; i++){
    if(abs(a[i]-average)%2 == 1){
        printf("-1"); 
        return 0;
    }
}
printf("%d", greedyAlg(a, average, n));
free(a);
return 0;

}

全部评论

相关推荐

10-15 09:13
已编辑
天津大学 soc前端设计
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务