POJ 2231 Moo Volume
来源:互联网 发布:阿里云香港服务器官网 编辑:程序博客网 时间:2024/06/05 14:32
这题用的是贪心算法来算的,贪心策略如下:
dist数组表示各个牛的位置距第一个牛的距离,当然之前要对牛的位置进行升序排序。
设a为第一头牛距各头牛的距离的总和,然后从第二头牛开始遍历,假设遍历到第i头牛时,那么标准为:
t=t-(n-i)*d+i*d,
各变量的含义为:t一开始为a,然后每次就是该表达式运算之后的值;
n为牛的总数;
d为第i头牛和第i-1头牛之间的距离。这个公式画图其实很好理解的。
把所有的t值加起来就是最后的结果。
#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>#include<stack>#include<queue>using namespace std;const int N=10005;int dist[N],cow[N];int main(){ int n; while(scanf("%d",&n)!=EOF) { for(int i=0;i<n;i++) scanf("%d",&cow[i]); sort(cow,cow+n); long long ans=0; for(int i=0;i<n;i++) { dist[i]=cow[i]-cow[0]; ans+=dist[i]; } long long temp=ans; for(int i=1;i<n;i++) { int d=dist[i]-dist[i-1]; temp=temp-(n-i)*d+i*d; //printf("%lld\n",temp); ans+=temp; } printf("%lld\n",ans); } return 0;}
0 0
- poj 2231 Moo Volume
- poj 2231 Moo Volume
- poj 2231 Moo Volume
- POJ 2231 Moo Volume
- POJ -- 2231 Moo Volume
- POJ 2231 Moo Volume
- poj 2231 Moo Volume
- POJ 2231 Moo Volume
- poj 2231Moo Volume
- POJ 2231 Moo Volume
- POJ 2231-Moo Volume
- poj 2231 Moo Volume
- poj 2231 Moo Volume
- POJ 2231 Moo Volume (暴力)
- poj 杂题 - 2231 Moo Volume
- POJ 2231:Moo Volume【细心】
- POJ 2231 Moo Volume【求和】
- POJ 2231 Moo Volume 笔记
- 06-0. 混合类型数据格式化输入(5)
- Commando War
- while(cin>>s)退出问题
- tomcat连接mysql发生中断的问题
- struts2常用标签
- POJ 2231 Moo Volume
- 源码管理十二:解决冲突
- Android项目中常用的工具类集
- Android之循环队列操作
- 分析并添加windows firewall规则的批处理
- CC2530的IO
- 电子书会推进纸质书的质与量
- servlet多线程的根本原因在于服务器端servlet是单实例的。
- STL容器适配器