Codeforces Release B-Fixed Points

Source: Internet
Author: User
Question: Given a sequence, there is an operation: the positions of two numbers are interchangeable. Q: Can I perform an operation at most once? What is the maximum number of [element position I] in a sequence that is equal to [element ai?

Based on the question, the maximum number is:

[The number of equal [element position I] and [element ai] before the operation]+ 【Swap two [element position I] and [element ai] elements that are not equal to the number of [element position I] and [element ai ].

For example:

0 1 2 4 3

This sequence is used to replace the following two elements so that each[Element position I] is equal to [element ai].

That is to say, you don't have to consider it when switching.[Element position I] is equal to [element ai].

Direct consideration[Element position I] is not equal to [element ai]Can one or two elements be swapped once?[Element position I] is equal to [element ai].

If one element exists after replacement[Element position I] is equal to [element ai]

So the maximum number=[Before the operation, the number of equal [element position I] and [element ai] is + 1. If two elements exist, the number is + 2.

Next we can use map to solve this problem.

#include <stdio.h>#include <map>using namespace std;int main(){    int n, ans;    while(~scanf("%d", &n))    {        map<int, int> mm;        ans = 0;        for(int i = 0; i < n; i++)        {            int temp;            scanf("%d", &temp);            if(temp == i)            {                ++ans;            }            else            {                mm[i] = temp;            }        }        map<int, int>::iterator it = mm.begin();        for(;it != mm.end();it++)        {            if(mm.find((*it).second) != mm.end() && mm[(*it).second] == (*it).first)            {                ++ans;                break;            }        }        if(ans != n)            ++ans;        printf("%d\n", ans);    }    return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.