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;}