Salem and Sticks-萨鲁曼的棍子 CodeForce#1105A 暴力
Posted saltyfishqf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于Salem and Sticks-萨鲁曼的棍子 CodeForce#1105A 暴力的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces Round #533 (Div. 2) A. Salem and Sticks(暴力)
LightOJ 1342 Aladdin and the Magical Sticks 期望(结论题)
POJ 2513 Colored Sticks(Tire+欧拉回(通)路判断)