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:
- For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
- For each station i there exists exactly one station j such that pj = 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 pi 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 p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Print one number — the maximum possible value of convenience.
3 2 1 3
9
5 1 5 4 3 2
17
In the first example the mayor can change p2 to 3 and p3 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 p2 to 4 and p3 to 5.
题意:给出一个铁路连接图,问最多改变两条路,可以联通的点对数(自己到自己也算)。
思路:题目给出了铁路规则,就是每个车站只有一个起点,这就保证了每一个内部联通(两两可达)
的站点集合都是一个环。为什么呢?看图:
比如1->2->3->4,
1.如果只有4个点,那么4的终点肯定是1,如果是2,3,4的话,那就不能保证每个点只有
一个起点。
2.如果还有别的点,4的终点指向1,没问题,是环。4的终点不指向1,也得指向2,3,4之外的点,
原因同1的描述。
所以一定构成环。没有额外分支。
对于一个环,联通点对就是环内点数n*(n-1) + n(自己到自己的点对)。其实也就是n^2
选出最大的两个联通环合成一个,可以让n^2最大。其它的环再加起来就可以了。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
#define PI acos(-1)
typedef long long ll;
#define INF 0x3f3f3f3f
int mod = 1000000007;
int rec[N];
bool vis[N];
int main()
{
int n;
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; i++)
scanf("%d", rec + i);
memset(vis, 0, sizeof(vis));
vector<int> v;
for (int i = 1; i <= n; i++) if (!vis[i])
{
int cur = i, cnt = 0;
while (!vis[i])
{
cnt++;
vis[i] = true;
i = rec[i];
}
v.push_back(cnt);
}
sort(v.begin(), v.end(), greater<int>());
if (v.size() < 2)
{
ll t = v[0];
t *= t;
cout<<t<<endl;
}else
{
ll t = v[0] + v[1];
t *= t;
// printf("%d %d>\n", v[0], v[1]);
for (int i = 2; i < v.size(); i++)
{
t += (ll)v[i]*v[i];
}
cout<<t<<endl;
}
}
return 0;
}