其他分享
首页 > 其他分享> > JZOJ 6958. 【2020.01.23冬令营模拟】国内战·剑鬼·魔法阵(环套树+结论)

JZOJ 6958. 【2020.01.23冬令营模拟】国内战·剑鬼·魔法阵(环套树+结论)

作者:互联网

JZOJ 6958. 【2020.01.23冬令营模拟】国内战·剑鬼·魔法阵

题目大意

题解

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 100010
#define ll long long
int v[N], vi[N], vis[N * 2], p[N], st[N][2], tot = 0;
int last[N], nxt[N * 2], to[N * 2], ls[N * 2], len = 1;
int c[2], a[N], sum = 0;
struct node {
	int l, r, s;
}cir[2][N], c0[N];
void add(int x, int y, int l) {
	to[++len] = y;
	nxt[len] = last[x];
	ls[len] = l;
	last[x] = len;
}
void dfs(int k, int fa) {
	vi[k] = 1;
	for(int i = last[k]; i; i = nxt[i]) if(!vis[i]) {
		vis[i] = vis[i ^ 1] = 1;
		if(!vi[to[i]]) {
			st[++tot][0] = k, st[tot][1] = ls[i];
			dfs(to[i], i);
			tot--;
		}
		else {
			int s = 1, j = tot;
			while(to[i] != k) {
				s++;
				if(st[j][0] == to[i]) break;
				j--;
			}	
			s %= 2;
			cir[s][++c[s]].l = sum + 1;
			cir[s][c[s]].r = sum + 1, cir[s][c[s]].s = 1;
			j = tot;
			a[++sum] = ls[i];
			while(to[i] != k) {
				a[++sum] = st[j][1];
				cir[s][c[s]].r++, cir[s][c[s]].s++;
				if(st[j][0] == to[i]) break;
				j--;
			}
		}
	}
}
int cmp(node x, node y) {
	return x.s > y.s;
}
int main() {
	int n, i, j, x;
	ll ans = 0;
	scanf("%d", &n);
	for(i = 1; i <= n; i++) scanf("%d", &v[i]);
	for(i = 1; i <= n; i++) {
		scanf("%d", &x);
		add(i, v[i], x), add(v[i], i, x);
		ans += x;
	}
	for(i = 1; i <= n; i++) if(!vi[i]) dfs(i, 0);
	for(i = 1; i <= sum; i++) ans -= a[i];
	for(i = 1; i <= c[1]; i++) {
		sort(a + cir[1][i].l, a + cir[1][i].r + 1);
		for(j = 0; j < cir[1][i].s / 2; j++) ans += a[cir[1][i].l + j] + a[cir[1][i].r - j];
	}
	for(i = 1; i <= c[0]; i++) {
		sort(a + cir[0][i].l, a + cir[0][i].r + 1);
		for(j = 0; j < cir[0][i].s / 2 - 1; j++) ans += a[cir[0][i].l + j] + a[cir[0][i].r - j];
		c0[i].l = a[cir[0][i].l + j];
		c0[i].r = a[cir[0][i].l + j + 1];
		c0[i].s = c0[i].r - c0[i].l;
	}
	sort(c0 + 1, c0 + c[0] + 1, cmp);
	for(i = 1; i <= c[0];) {
		ans += c0[i++].l;
		if(i > c[0]) break;
		ans += c0[i++].r;
	}
	printf("%lld\n", ans);
	return 0;
}

自我小结

标签:冬令营,23,2020.01,++,tot,cir,int,ans,c0
来源: https://blog.csdn.net/qq_39565901/article/details/113484239