NKOJ [USACO4.1]篱笆回路Fence Loops【dfs】

这么小的数据范围写什么强行边转点跑最小环,暴力dfs就好了。

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define repd(i,x,y) for(ll i=(x);i>=(y);i--)
using namespace std;

const ll N=1e4+5;
const ll Inf=1e18;

ll n,m,ans=Inf,v[N],vis[N],sum[N];
ll cnt,to[N],nxt[N],head1[N],head2[N];

inline ll read() {
	ll x=0;char ch=getchar();bool f=0;
	while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?-x:x;
}

void ins1(ll x,ll y) {
	to[++cnt]=y;nxt[cnt]=head1[x];head1[x]=cnt;
}

void ins2(ll x,ll y) {
	to[++cnt]=y;nxt[cnt]=head2[x];head2[x]=cnt;
}

bool check1(ll x,ll y) {
	ll p=head1[x];
	while(p) {
		if(to[p]==y) return false;
		p=nxt[p];
	}
	return true;
}

bool check2(ll x,ll y) {
	ll p=head2[x];
	while(p) {
		if(to[p]==y) return false;
		p=nxt[p];
	}
	return true;
}

void dfs(ll x,ll y,ll z) {
	if(vis[x]) {
		ans=min(ans,z-sum[x]);return ;
	}vis[x]=1;sum[x]=z;
	
	if(check1(x,y)) {
		ll p=head1[x];
		while(p) {
			if(to[p]!=y) dfs(to[p],x,z+v[x]);
			p=nxt[p];
		}
	}
	
	if(check2(x,y)) {
		ll p=head2[x];
		while(p) {
			if(to[p]!=y) dfs(to[p],x,z+v[x]);
			p=nxt[p];
		}
	}
	
	vis[x]=0;
}

int main() {
	n=read();
	
	rep(i,1,n) {
		ll id=read(),z=read(),m1=read(),m2=read();
		v[id]=z;
		
		rep(i,1,m1) {
			ll p=read();ins1(id,p);
		}
		rep(i,1,m2) {
			ll p=read();ins2(id,p);
		}
	}
	
	dfs(1,-1,0);
	
	printf("%lld",ans);
	
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值