luogu 1327 数列排序

题意

给定一个数列\(\{an\}\),这个数列满足\(ai≠aj(i≠j)\),现在要求你把这个数列从小到大排序,每次允许你交换其中任意一对数,请问最少需要几次交换?

思路

找循环节。答案即为 (循环节的长度\(-1\)) 对所有循环节求和。

如果只能交换相邻两个,那么就是求逆序对个数。因为交换相邻两个数字的效果是使逆序对个数\(-1\).

Code

#include <bits/stdc++.h>
#define maxn 100010
using namespace std;
typedef long long LL;
int a[maxn], b[maxn];
bool vis[maxn];
map<int, int> mp;
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
b[i] = a[i];
mp[a[i]] = i;
}
sort(b, b+n);
int ans = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
int j = i;
while (!vis[j]) {
vis[j] = true;
j = mp[b[j]];
++ans;
}
--ans;
}
printf("%d\n", ans);
return 0;
}

2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 J.Minimum Distance in a Star Graph

题意

给出一个排列,问对其进行多少次操作能得到递增的排列。

一次操作指交换第\(i\)个位置上的数和第\(1\)个位置上的数。

思路

找循环节。

对于包含第一个数字的循环节,交换次数为 (循环节长度\(-1\));\(otherwise\),交换次数为 (循环节长度\(+1\)).

Code

#include <bits/stdc++.h>
using namespace std;
#define maxn 1010 int n;
char s[100], t[100];
int pos[maxn];
bool vis[maxn]; void work() {
char ch;
memset(vis, 0, sizeof(vis));
memset(pos, 0, sizeof(pos));
scanf("%s%s", s, t);
for (int i = 0; i < n; ++i) pos[s[i]] = i;
int temp = 0, ans = 0; vis[0] = true;
while (t[temp] != s[0]) {
temp = pos[t[temp]];
++ans;
vis[temp] = true;
} for (int i = 1; i < n; ++i) {
if (!vis[i]) {
vis[i] = true;
int temp = i, len = 0;
while (t[temp] != s[i]) {
temp = pos[t[temp]];
++len;
vis[temp] = true;
}
if (len) ans += len + 2;
}
}
printf("%d\n", ans);
} int main() {
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < 5; ++i) work();
}
return 0;
}

最新文章

  1. python 模块基础介绍
  2. 广搜+打表 POJ 1426 Find The Multiple
  3. Microsoft.ACE.OLEDB.12.0 错误 上传读取Excel错误
  4. cimge 这次能够图片大小尺寸
  5. LA 6450 Social Advertising
  6. ubuntu 下关闭MySql server
  7. 面向对象的方式进行数据交换网络之间的差异--无缝切换的发展到单机游戏C/S模式
  8. nfs+rsync+inotify实现文件的实时同步
  9. Sqlserver如何递归查询层级数据将父级字段和本级某个字段合并?如何自定义用户函数并调用?
  10. 解决ios不支持按钮:active伪类的方法
  11. 依赖背包——cf855C好题
  12. WebWorker与WebSocket实现前端消息总线
  13. pytorch预训练
  14. LinQ是什么?
  15. 咏南中间件JSON序列类
  16. sftp服务器的安装与远程
  17. php notes
  18. Path Sum II - LeetCode
  19. jenkins Email-ext plugin插件中Pre-send Script设置说明
  20. 简单实现MemCachedUtil

热门文章

  1. cocos2dx 使用XMLHttpRequest时回调status为0的问题
  2. React组件自适应窗口宽高
  3. 【Git版本控制】GitHub上fork项目和clone项目的区别
  4. 【MySQL】mac环境下使用navicat premium连接mysql乱码问题
  5. Anaconda安装和环境的搭建
  6. 使用nohup+&amp; 踩到的坑
  7. UVALive - 8292 (法里数列)
  8. myeclipse中hibernate生成映射文件
  9. asynctask 异步下载
  10. 大数据学习——spark笔记