hdu 2838 Cow Sorting
来源:互联网 发布:大数据分析书籍推荐 编辑:程序博客网 时间:2024/05/02 04:42
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2838
题目大意:有n头(1<=n<=100,000)牛,每头牛有一个不同的rank(1<=rank<=100,000),牛的主人要按照rank给牛排序,并且只有相邻的牛能交换位置,且如果牛i和牛j交换,那么要话费的时间是rank[i]+rank[j],求最小花费的时间.
思路:因为相邻的牛才能交换,那么把rank小的先换到其最终位置就能保证时间最小,因为如果有个rank大的先别换到其最终位置但是还有一个rank小的在它后面,那么rank大的必然还要再交换.
用线段树或树状数组快速求需要交换的牛的rank和sum和需要交换的牛的头数cnt.
那么把牛x换到其最终位置的时间=sum[x]+cnt[x]*rank[x],换到最终位置后就把牛x所在的原位置清零.
代码:
#include <stdlib.h>#include <string.h>#include <stdio.h>#include <ctype.h>#include <math.h>#include <time.h>#include <stack>#include <queue>#include <map>#include <set>#include <vector>#include <string>#include <iostream>#include <algorithm>using namespace std;#define ull unsigned __int64#define ll __int64//#define ull unsigned long long//#define ll long long#define lson l,mid,rt<<1#define rson mid+1,r,rt<<1|1#define middle (l+r)>>1#define mod 1000000#define esp (1e-10)const int INF=0x3F3F3F3F;//const double pi=acos(-1.0);const int N=100010;int n,m,cnt[N];ll sum[N];struct node{ ll lv; int pos; bool operator < (const node& p) const { return lv < p.lv; }}a[N];int lowbit(int x){return x&(-x);}void Update(int x,ll c1,int c2){ while(x<=n) sum[x]+=c1,cnt[x]+=c2,x+=lowbit(x);}void Query(int x,ll& r1,int& r2){ r1=r2=0; while(x>0) r1+=sum[x],r2+=cnt[x],x-=lowbit(x);}int main(){ //freopen("1.in","r",stdin); //freopen("1.out","w",stdout); int i,j,k,r2; ll ret,r1; char op[2]; //int T,cas;scanf("%d",&T);for(cas=1;cas<=T;cas++) while(~scanf("%d",&n)){ for(i=1;i<=n;i++){ scanf("%I64d",&a[i].lv),a[i].pos=i; Update(i,a[i].lv,1); } sort(a+1,a+n+1); for(i=1,ret=0;i<=n;i++){ Update(a[i].pos,-a[i].lv,-1); Query(a[i].pos,r1,r2); ret+=r1+r2*a[i].lv; } printf("%I64d\n",ret); } return 0;}
- hdu 2838 Cow Sorting
- hdu 2838 Cow Sorting
- HDU 2838 Cow Sorting
- hdu 2838 Cow Sorting
- POJ 3270 / HDU 2838 - Cow Sorting
- HDU 2838 cow sorting 树状数组
- hdu 2838 Cow Sorting(树状数组)
- hdu 2838 Cow Sorting(树状数组)
- hdu 2838 Cow Sorting (树状数组)
- HDU 2838 Cow Sorting(树状数组)
- hdu-2838(Cow Sorting)----》树状数组
- HDU - 2838 Cow Sorting (树状数组)
- hdu 2838 Cow Sorting(树状数组)
- hdu 2838 cow sorting(树状数组)
- hdu 2838 Cow Sorting 树状数组
- HDU 2838 Cow Sorting(树状数组)
- HDU-2838 Cow Sorting(树状数组)
- HDU 2838 Cow Sorting 树状数组
- poj 1928 The Peanuts
- java 实验七 之 阿拉伯整数转换为中文大写数字(注意读法)
- 贪吃蛇游戏
- object references an unsaved transient instance - save the transient instance before flushing
- C++ 日志类,
- hdu 2838 Cow Sorting
- 为了防止爆内存,UIImageView在release之前,还是要把image置nil
- ACM术语(不断整理中)
- shell文件权限问题
- POJ 1019 Number Sequence
- 获取Android SDK 源代码并在Eclipse中关联查看的方法
- 对Oracle 11用户进行解锁
- django操作数据库使用中文的方法
- Linux重定向(待整理)