当前位置:网站首页>Three methods of finding inverse numbers
Three methods of finding inverse numbers
2022-07-01 23:52:00 【why151】
Violence law
#include<iostream>
#include<algorithm>
using namespace std;
int a[2010];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
if(a[i]>a[j]) ans+=1;
}
cout<<ans<<endl;
return 0;
}
Merge sort
#include<iostream>
#include<algorithm>
using namespace std;
int a[2010],q[2010];
int ans=0;
void arrange_sort(int l,int r)
{
if(l>=r) return;
int mid=l+r>>1;
arrange_sort(l,mid);
arrange_sort(mid+1,r);
int k=0;
int i=l,j=mid+1;
while(i<=mid&&j<=r)
{
// cout<<i<<' '<<j<<' '<<l<<' '<<r<<' '<<a[i]<<' '<<a[j]<<endl;
if(a[i]<=a[j]) q[++k]=a[i++];
else
{
q[++k]=a[j++];
ans+=mid-i+1;
}
}
while(i<=mid) q[++k]=a[i++];
while(j<=r) q[++k]=a[j++];
for(int i=l,j=1;j<=k;j++,i++)
a[i]=q[j];
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
arrange_sort(1,n);
cout<<ans<<endl;
}
Tree array method
#include<algorithm>
#include<iostream>
#include<unordered_map>
using namespace std;
unordered_map<int,int> a;
int lowbit(int x)
{
return x&-x;
}
void insert(int x,int k)
{
while(x<=0x3f3f3f3f)
{
a[x]+=k;
x+=lowbit(x);
}
}
int query(int x)
{
int ans=0;
while(x)
{
ans+=a[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
int n;
cin>>n;
int ans=0;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
insert(x,1);
ans+=i-query(x);
}
cout<<ans<<endl;
}
边栏推荐
猜你喜欢
牛客-练习赛101-推理小丑
Know --matplotlib
比较通俗易懂的PID理解
写给当前及未来博士研究生一些建议整理分享
.env.xxx 文件,加了常量,却undefined
How to solve the image pop-up problem when pycharm calls Matplotlib to draw
[QT] qtcreator uninstall and installation (abnormal state)
RPA tutorial 01: Excel automation from introduction to practice
Pytorch learning record
TS初次使用、ts类型
随机推荐
【QT】测试Qt是否能连接上数据库
求逆序数的三个方法
常见的积分商城游戏类型有哪些?
[leetcode] length of the last word [58]
Windows installation WSL (II)
algolia 搜索需求,做的快自闭了...
Windows 7 install MySQL error: 1067
sql 优化
[LeetCode] 最后一个单词的长度【58】
Is it safe to buy funds on Great Wall Securities?
2021 robocom world robot developer competition - preliminary competition of undergraduate group
cookie、session、tooken
Redis AOF日志
[es practice] safe operation mode on ES
ADO. Net SqlCommand object
[QT] qtcreator uninstall and installation (abnormal state)
SecurityUtils.getSubject().getPrincipal()为null的问题怎么解决
The best smart home open source system in 2022: introduction to Alexa, home assistant and homekit ecosystem
门级建模—课后习题
2021 RoboCom 世界机器人开发者大赛-本科组初赛