【题解】洛谷P3275(bzoj2330)[SCOI2011]糖果 差分约束

题目链接
在这里插入图片描述
在这里插入图片描述


设每个小朋友得到的糖果数为 c c c
{ x = 1 c a − c b ≥ 0 且 c b − c a ≥ 0 x = 2 c b − c a ≥ 1 x = 3 c a − c b ≥ 0 x = 4 c a − c b ≥ 1 x = 5 c b − c a ≥ 0 \begin{cases}x=1\quad c_a-c_b\geq0且c_b-c_a\geq0\\x=2\quad c_b-c_a\geq1\\x=3\quad c_a-c_b\geq0\\x=4\quad c_a-c_b\geq1\\x=5\quad c_b-c_a\geq0\end{cases} x=1cacb0cbca0x=2cbca1x=3cacb0x=4cacb1x=5cbca0
差分约束即可。注意此题有长链卡spfa,想办法卡卡就过了(好像还挺快)

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int N=1e5+10;
namespace IO{
	template<class T>inline void read(T&x)
	{
		x=0;int f=0;char ch=getchar();
		while(ch<'0'||ch>'9')f|=ch=='-',ch=getchar();
		while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
		if(f)x=-x;
	}
	template<class M>inline void write(M x)
	{
		static int buf[40],p=0;
		if(x<0)putchar('-'),x=-x;
		do{
			buf[p++]=x%10;x/=10;
		}while(x);
		for(int i=p-1;i>=0;i--)putchar(buf[i]+'0');
		putchar('\n');
	}
}
int n,k,hd[N],tot,dis[N],vis[N],cnt[N];
ll ans;
struct Edge{
    int v,w,nx;
}e[N<<2];
inline void add(int u,int v,int w)
{
    e[++tot].v=v;
    e[tot].w=w;
    e[tot].nx=hd[u];
    hd[u]=tot;
}
inline bool spfa()
{
    memset(dis,0xcf,sizeof(dis));
    dis[0]=0;queue<int>q;q.push(0);vis[0]=1,cnt[0]=1;
    for(int i=1;i<=n;i++)q.push(i),vis[i]=1;
    while(q.size())
    {
        int u=q.front();q.pop();vis[u]=0;
        for(int i=hd[u];i;i=e[i].nx)
        {
            int v=e[i].v;
            if(dis[v]<dis[u]+e[i].w)
            {
                dis[v]=dis[u]+e[i].w;cnt[v]++;
                if(cnt[v]>=n)return false;
                if(!vis[v])vis[v]=1,q.push(v);
            }
        }
    }
    return true;
}
int main()
{
    //freopen("in.txt","r",stdin);
    using namespace IO;
    read(n);read(k);
    while(k--)
    {
        int x,a,b;
        read(x);read(a);read(b);
        switch(x)
        {
            case 1:add(a,b,0),add(b,a,0);break;
            case 2:{
                if(a==b)return puts("-1"),0;
                else add(a,b,1);break;
            }
            case 3:add(b,a,0);break;
            case 4:{
                if(a==b)return puts("-1"),0;
                else add(b,a,1);break;
            }
            case 5:add(a,b,0);break;
        }
    }
    for(int i=1;i<=n;i++)
        add(0,i,1);
    if(!spfa())puts("-1");
    else
    {
        for(int i=1;i<=n;i++)
            ans+=dis[i];
        write(ans);
    }
    return 0;
}

总结

把不等关系列出来,差分约束连边跑单源最长路即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值