Bertown Subway

题意翻译

给你1-n的一个排列a,你从某一个位置a[i]可以到达a[a[i]],我们定义便利度为令i和j都从1-n,从i能到达j的pair的对数(也包括i到i)。 市长想要改变这个排列使得它的便利度最大,但是他最多只能改变两个数字,并且改变完之后的排列也必须是1-n不重复的。求能得到的最大便利值。

题目描述

The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself. There are $ n $ stations in the subway. It was built according to the Bertown Transport Law: 1. For each station $ i $ there exists exactly one train that goes from this station. Its destination station is $ p_{i} $ , possibly $ p_{i}=i $ ; 2. For each station $ i $ there exists exactly one station $ j $ such that $ p_{j}=i $ . The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs $ (x,y) $ such that person can start at station $ x $ and, after taking some subway trains (possibly zero), arrive at station $ y $ ( $ 1<=x,y<=n $ ). The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of $ p_{i} $ for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes. The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!

输入输出格式

输入格式


The first line contains one integer number $ n $ ( $ 1<=n<=100000 $ ) — the number of stations. The second line contains $ n $ integer numbers $ p_{1} $ , $ p_{2} $ , ..., $ p_{n} $ ( $ 1<=p_{i}<=n $ ) — the current structure of the subway. All these numbers are distinct.

输出格式


Print one number — the maximum possible value of convenience.

输入输出样例

输入样例 #1

3
2 1 3

输出样例 #1

9

输入样例 #2

5
1 5 4 3 2

输出样例 #2

17

说明

In the first example the mayor can change $ p_{2} $ to $ 3 $ and $ p_{3} $ to $ 1 $ , so there will be $ 9 $ pairs: $ (1,1) $ , $ (1,2) $ , $ (1,3) $ , $ (2,1) $ , $ (2,2) $ , $ (2,3) $ , $ (3,1) $ , $ (3,2) $ , $ (3,3) $ . In the second example the mayor can change $ p_{2} $ to $ 4 $ and $ p_{3} $ to $ 5 $ .