Kuglarz 题解

建图

知道 \([l,r_1]\) 奇偶性和 \([l,r_2]\) 奇偶性,必然知道 \([r_1+1,r_2]\)的奇偶性这很像是图上连边, \((u,v) (v,w) --> (u,w)\) 但这里有个+1,我们考虑去掉,那么就是每条边\([l,r]\) 都连边 \((l-1,r)\)然后全图跑最小生成树求最小代价

#include <queue>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
const int N=2005;
const int inf=0x3f3f3f3f;
inline int read() {
	int x=0;char ch=getchar();
	while(ch<'0'||ch>'9')ch=getchar();
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x;
}
 
int n;
int hd[N],to[N*N],nxt[N*N],w[N*N],tot;
inline void add(int x,int y,int z) {
	to[++tot]=y;w[tot]=z;nxt[tot]=hd[x];hd[x]=tot;
}
struct node{
	int x,y,z;
	bool operator < (const node &w) const {
		return z<w.z;
	}
}e[N*N];
int fa[N];
inline int find(int x) {
	return x==fa[x]?x:fa[x]=find(fa[x]);
}
int cnt;
ll sum=0;
void kru() {
	sort(e+1,e+1+cnt);
	int ans=0;
	for(int i=1;i<=cnt;i++) {
		int x=find(e[i].x),y=find(e[i].y);
		if(x==y)continue;
		fa[x]=y;
		sum+=e[i].z;
		if(++ans==n) return;
	}
}
int main() {
	n=read();
	for(int i=1;i<=n;i++) fa[i]=i;
	for(int i=1;i<=n;i++) 
		for(int j=i;j<=n;j++) 
			e[++cnt].x=i-1,e[cnt].y=j,e[cnt].z=read();
	kru();
	printf("%lld\n",sum);
	return 0;
}
posted @ 2020-10-27 16:00  ke_xin  阅读(23)  评论(0编辑  收藏  举报