F - Bertown Subway

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 pi, possibly pi = i;
  2. 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!

#include
#include
#define int long long
const int maxn = 1e5 + 10;
int a[maxn], b[maxn];
bool vis[maxn];
int n, ans, cnt;
int dfs(int star,int next,int res)
{
  return vis[next] ? res : (vis[next] = true,dfs(star, a[next],res + 1));
}

signed main()
{
  std::cin >> n;
  for(int i = 1;i <= n;i++)
  std::cin >> a[i];
  for(int i = 1;i <= n;i++)
  if(!vis[i])vis[i] = true,b[cnt++] = dfs(i,a[i],1);
  std::sort(b,b + cnt);
  for(int i = 0;i < cnt - 2;i++)ans += b[i] * b[i];
  std::cout << ans + (b[cnt - 1] + b[cnt - 2]) * (b[cnt - 1] + b[cnt - 2]) << std::endl;
  return 0;
}

你可能感兴趣的:(洛谷题目集,算法)