Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.
The operation of changing a number's sign is the operation of multiplying this number by -1.
Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
The first line contains two integers n and k (1 ≤ n, k ≤ 105), showing, how many numbers are in the sequence and how many swaps are to be made.
The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≤ 104).
The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.
3 2
-1 -1 1
3
3 1
-1 -1 1
1
In the first sample we can get sequence [1, 1, 1], thus the total income equals 3.
In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.
先对数组排序,一开始用冒泡,结果超时了QAQ,改快排了。然后分两种情况,负数大于等于 change次数的 直接把负数从小到大依次change。负数比change次数小的,把负数都change,再排序,剩下change次数都对最小的数操作。
附代码:
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 int arr[100000]={0}; 5 6 int cmp(const void *a,const void *b) 7 { 8 return *(int *)a-*(int *)b; 9 } 10 11 int main(void) 12 { 13 int n, k, i, j, sum=0, count=0; 14 int temp; 15 16 scanf("%d %d", &n, &k); 17 for( i=0; i<n; i++) 18 { 19 scanf("%d", &arr[i]); 20 if( arr[i]<0 ) 21 count++; 22 } 23 qsort( arr, n, sizeof(int), cmp); 24 if( count>k) 25 { 26 for( i=0; i<k; i++) 27 arr[i]*=-1; 28 } 29 else if( count == k) 30 { 31 for( i=0; i<k; i++) 32 arr[i]*=-1; 33 } 34 else 35 { 36 for( i=0; i<count; i++) 37 arr[i]*=-1; 38 qsort( arr, n, sizeof(int), cmp); 39 for( i=0; i<(k-count); i++) 40 arr[0]*=-1; 41 } 42 for( i=0; i<n; i++) 43 sum+=arr[i]; 44 printf("%d", sum); 45 return 0; 46 }