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 }

 

转载于:https://www.cnblogs.com/SaltyFishQF/p/10327496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值