Salem and Sticks-萨鲁曼的棍子 CodeForce#1105A 暴力

题目链接:Salem and Sticks

题目原文


Salem gave you 𝑛n sticks with integer positive lengths 𝑎1,𝑎2,,𝑎𝑛a1,a2,…,an.

For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from 𝑎 to 𝑏 is |𝑎𝑏|, where |𝑥| means the absolute value of 𝑥.

A stick length 𝑎𝑖 is called almost good for some integer 𝑡 if |𝑎𝑖𝑡|1|ai−t|≤1.

Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer 𝑡 and the total cost of changing is minimum possible. The value of 𝑡 is not fixed in advance and you can choose it as any positive integer.

As an answer, print the value of 𝑡 and the minimum cost. If there are multiple optimal choices for 𝑡, print any of them.

题目大意

假设棍子长度为a,把棍子改成b的花费是|a-b|。(无论增长还是缩短)

现在有n根棍子,要用最小的开销c,使n根棍子的长度都在区间[t-1, t+1]内。如果有多组解,求出任一即可。

思路

这个题目的数据范围不大,n<1000, a<100。找出 t = (1, max(a)) 时的所有开销c,并记录最小的一组(ti, ci)值。

题解

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 int num, maxd, ans = 0x3f3f3f3f, ans_i;
 6 int a[1005];
 7 
 8 int main(int argc, char const *argv[])
 9 {
10 #ifdef debug
11     freopen("test.txt", "r", stdin);
12 #endif
13     cin >> num;
14     for(int i = 0; i < num; i++)
15     {
16         cin >> a[i];
17         if(a[i] > maxd)
18         {
19             maxd = a[i];
20         }
21     }
22 
23     for(int i = 1; i <= maxd; i++)
24     {
25         int flag = 0;
26         for(int j = 0; j < num; j++)
27         {
28             if(a[j] > i + 1)
29             {
30                 flag += a[j] - i - 1;
31             }
32             if(a[j] < i - 1)
33             {
34                 flag += i - a[j] - 1; 
35             }
36         }
37         if(flag < ans)
38         {
39             ans = flag;
40             ans_i = i;
41         }
42         if(flag == 0)
43         {
44             break;
45         }
46     }
47     cout << ans_i << " " << ans;
48     return 0;
49 }

 

posted @ 2019-01-27 17:54  SaltyFishQF  阅读(255)  评论(0编辑  收藏  举报