惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Privacy & Cybersecurity Law Blog
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
爱范儿
爱范儿
博客园 - 司徒正美
量子位
Recent Commits to openclaw:main
Recent Commits to openclaw:main
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园_首页
月光博客
月光博客
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
Hacker News: Ask HN
Hacker News: Ask HN
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
H
Heimdal Security Blog
小众软件
小众软件
Attack and Defense Labs
Attack and Defense Labs
V
Visual Studio Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cloudbric
Cloudbric
Stack Overflow Blog
Stack Overflow Blog
L
LINUX DO - 最新话题
Forbes - Security
Forbes - Security
Last Week in AI
Last Week in AI
阮一峰的网络日志
阮一峰的网络日志
W
WeLiveSecurity
IT之家
IT之家
U
Unit 42
H
Hacker News: Front Page
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Announcements
Recent Announcements
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
Google Developers Blog
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
S
Schneier on Security
F
Fortinet All Blogs
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs

Makerlife 的小站

2025-2026 赛季 游记 && 退役记 NOIP 2024 游记 集训记录 CSP2024 游记 板子库 动态规划 刷题记录 杂题乱记 数学期望 学习笔记 数论 学习笔记 CF1000F One Occurrence 题解 P6878 [JOI 2020 Final] JJOOII 2 题解 CSP2023 游寄 主定理 CF1695C Zero Path 题解 字符串算法全家桶 学习笔记 AT_ABC306D 题解 2023.06.03 模拟赛 Azure for Students 使用指北 AT_ABC286C 题解 洛谷 AT1898 题解 洛谷 CF1036A 题解 洛谷 CF1040A 题解 洛谷 SP3591 题解 洛谷 AT278 题解 洛谷 CF141B 题解 洛谷 AT2561 题解 洛谷 CF899B 题解 洛谷 AT4787 题解 洛谷 AT4810 题解 洛谷 SP5450 题解
洛谷 AT3525 题解
Makerlife · 2022-02-07 · via Makerlife 的小站

洛谷题目传送门 | AT 原题传送门

思路

分析题目可以很简单地得到,如果满足 pi=ip_i=i 的条件,那么交换 pip_ipi+1p_{i+1} 后得到的结果一定是最优解。

我们要做的只是从前到后遍历一遍 pp 数组,如果 pi=ip_i=i 就交换 pip_ipi+1p_{i+1},同时 ansans 累加。

看到楼下有大佬说当 i=ni=n 是需要特判,但其实完全不需要,只要数组开的够大,也不会在交换 pnp_npn+1p_{n+1} 时发生越界情况。但为了严谨也可以特判。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int n,p[100010];
int ans=0;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&p[i]);
}
for(int i=1;i<=n;i++)
{
if(p[i]==i)
{
ans++;//答案数量增加
swap(p[i],p[i+1]);//交换p[i]和p[i+1]
}
}
printf("%d\n",ans);
return 0;
}