Codeforces 347 B Fixed Points 题解

题目连接:http://codeforces.com/problemset/problem/456/B

一道很容易出错的简单题。反正我是WA了几次。

主要会出错的地方是,如何记录下标和值的对应关系,然后判断swap之后,两个值就是到位了(fixed points)。如 0 1 4 3 2 6 7 5,如何判断swap2和4之后,2和4就是到位了。我使用新的数列记录了原来数组的值对应到原来数组的下标。直接使用map也是可以的,但是速度就慢了。

这是个简单的逻辑,思维却有点绕,最好举多几个例子。


#include <stdio.h>
#include <vector>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <limits.h>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;

const int MAX_N = (int) 1E5+1;
int arr[MAX_N], a2[MAX_N];

int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		scanf("%d", arr+i);
	}
	int ans = 0;
	for (int i = 0; i < n; i++)
	{
		if (i == arr[i]) ans++, a2[i] = -1;
		else a2[arr[i]] = i;
	}
	if (ans == n)//ans 不可能等于 n-1
	{
		printf("%d", ans);
		return 0;
	}
	printf("\n");
	ans++;
	for (int i = 0; i < n; i++)
	{
		if (i != arr[i])
		{
			int j = a2[i];//这里的逻辑需要非常细心,很容易出先头疼的错误
			if (a2[j] == i)
			{
				ans++;
				break;
			}
		}
	}
	printf("%d", ans);
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值