The problem is from codeforces: http://codeforces.com/problemset/problem/347/B
It has been a while and I just pick another easy math problem to update the blog. The problem states that only maximum 1 swap is allowed, and that leads three possible outcomes: 0, 1, or 2.
The zero means that the original permutation series is perfect, it has all numbers in place, and no more fixed points can be found after swapping (in fact, it will reduce by two if swap any two)
The ‘1’ means that we can increase the number of fixed points by only one if swapping any two.
The best case (‘2’) would be after swapping, two more fixed points can be acquired. This is due to that one number should be at the other and vice versa.
The solution is simple but you have to be careful enough to pass all tests at first try. In my case, I didn’t consider the ‘0’ case and it failed me at test 11.
#!/bin/env python #https://helloacm.com #http://codeforces.com/problemset/problem/347/B n = int(raw_input()) a = map(int, raw_input().split()) c = 0 f = True for x in xrange(n): if a[x] != x: if f and (a[a[x]] == x): c += 2 f = False else: c += 1 if c == n: print c else: print c if (not f) else c + 1
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: VBScript Browse for Folder using Shell.Application Object
Next Post: CRC32 Calculator (Javascript)