Sort it hdu 2689
来源:互联网 发布:e4a操作数据库 编辑:程序博客网 时间:2024/05/21 11:19
Problem Description
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
Output
For each case, output the minimum times need to sort it in ascending order on a single line.
Sample Input
31 2 34 4 3 2 1
Sample Output
06
简单的一个水题,第一次看到的时候 直接暴力俩for循环计数下就ac了。
。 但是 后来用了树状数组来写,发现真的很神奇。理解下题意。就是看
输入的时候的数前面有几个逆序数,存入数组,然后 求1到n的逆序数个数。
注意输入的时候是先更新 ,防止最后一个未算入。
暴力写法:
#include<iostream>#include<cstring>#include<cstdlib>#include<string>using namespace std;int main(){int n,i,j;int s[1010];while(cin>>n){for(i=0;i<n;i++){cin>>s[i];}int tot=0;for(i=0;i<n;i++){for(j=i+1;j<n;j++){if(s[i]>s[j]){int t=s[i];s[i]=s[j];s[j]=t;tot++;}}}cout<<tot<<endl;}return 0;}
树状数组写法
#include<iostream>#include<cstring>using namespace std;int s[1010],n;int lowbit(int x){return x&(-x);}int sum(int x){int suM=0;while(x>0){suM+=s[x];x-=lowbit(x);}return suM;}void updata(int x){while(x<=n){++s[x];x+=lowbit(x);}}int main(){int i,m;while(cin>>n){memset(s,0,sizeof(s));int ans=0;for(i=1;i<=n;i++){cin>>m;updata(m);ans+=sum(n)-sum(m);}cout<<ans<<endl;}return 0;}
0 0
- hdu 2689 Sort it
- hdu 2689 Sort it
- HDU 2689 Sort it
- HDU-2689-Sort it
- hdu 2689 Sort it
- Sort it hdu 2689
- HDU 2689 Sort it
- hdu 2689 Sort it
- HDU-2689-Sort it
- hdu 2689 Sort it
- hdu 2689 sort it
- 【HDU 2689】【水题】Sort it
- 杭电ACM HDU 2689 Sort it
- HDU 2689 sort it - from lanshui_Yang
- hdu 2689 Sort it(线段树)
- HDU 2689 Sort it (树状数组)
- HDU 2689 Sort it [树状数组]【数据结构】
- hdu 2689 Sort it(树状数组)
- 8.建立root以外的管理员用户
- VDA FunctionalLevel too low for Catalog
- IOC前世今生
- 学习记录:linux下将C程序编译为汇编程序进行分析
- 开发中常用服务集合(已完结)
- Sort it hdu 2689
- select into from与insert into select区别详解,sql语句复制表
- canvas笔记1
- python类基本语法笔记
- Oracle分组ROLLUP、GROUP BY、GROUPING、GROUPING SETS区别和作用
- GC调优在Spark应用中的实践
- IOS中的线程操作(3)
- 在 Mac OS X 10.10 安装 pyenv 的一个小坑
- TP分页 (3.1) — 其中,获取当页页需要在类库中加取方法