【Educational Codeforces Round 31 C】Bertown Subway

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

最后肯定会形成若干个环的。 把最大的两个环合在一起就好。 每个环贡献: 假设x=环的大小 ->x*x 注意int的溢出

【代码】

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5;

int n,a[N+10];
bool flag[N+10];
vector <long long> v;

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("rush_in.txt", "r", stdin);
	#endif
	scanf("%d",&n);
	for (int i = 1;i <= n;i++){
	 	scanf("%d",&a[i]);
	}
	for (int i = 1;i <= n;i++){
	 	if (!flag[i]){
	 	 	int now = i;
	 	 	int cnt = 0;
	 	 	while (!flag[now]){
	 	 	 	flag[now] = 1;
	 	 	 	cnt++;
	 	 	 	now = a[now];
	 	 	}
			v.push_back(cnt);
	 	}
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
	if ( (int) v.size()==1){
	 	printf("%lld\n",v[0]*(v[0]-1)+v[0]);
	}else{
		long long temp = v[0]+v[1];
		temp = 1LL*(temp-1)*temp + temp;
		for (int i = 2;i < (int) v.size();i++){
		 	temp += v[i]*(v[i]-1)+v[i];
		}
		printf("%lld\n",temp);
	}

	return 0;
}
posted @ 2017-11-10 11:34  AWCXV  阅读(115)  评论(0编辑  收藏  举报