bzoj2330 糖果 差分约束

           简单的差分约束系统。a-b>=c转化为b->a连一条长度为c的边,跑最长路,这样可以保证满足不等号。a=b转化为a>=b且b>=a即可。spfa判正权回路即可。

       P·S:一个m打成n查了半天。。汗(⊙﹏⊙)b。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
#define N 400005
using namespace std;

int n,m,tot,fst[N],pnt[N],len[N],nxt[N],d[N],h[N],sum[N];
bool bo[N];
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;
}
void add(int aa,int bb,int cc){
	pnt[++tot]=bb; len[tot]=cc; nxt[tot]=fst[aa]; fst[aa]=tot;
}
bool spfa(){
	int head=0,tail=n,i;
	for (i=1; i<=n; i++){ h[i]=i; d[i]=sum[i]=1; }
	while (head!=tail){
		head=(head+1)%N;
		int x=h[head],p; bo[x]=1;
		for (p=fst[x]; p; p=nxt[p]){
			int y=pnt[p];
			if (d[x]+len[p]>d[y]){
				d[y]=d[x]+len[p];
				sum[y]++; if (sum[y]>n) return 0;
				if (bo[y]){
					bo[y]=0; tail=(tail+1)%N;
					h[tail]=y;
				}
			}
		}
	}
	return 1;
}
int main(){
	n=read(); m=read(); int i;
	for (i=1; i<=m; i++){
		int k=read(),x=read(),y=read();
		if (k==1){ add(x,y,0); add(y,x,0); } else
		if (k==2){ if (x==y){ puts("-1"); return 0; } add(x,y,1); } else
		if (k==4){ if (x==y){ puts("-1"); return 0; } add(y,x,1); } else
		if (k==3) add(y,x,0); else add(x,y,0);
	}
	if (!spfa()) puts("-1"); else{
		ll ans=0; for (i=1; i<=n; i++) ans+=(ll)d[i];
		printf("%lld\n",ans);
	}
	return 0;
}<em>
</em>

2015.11.28

by lych

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值