设每个小朋友得到的糖果数为
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=1ca−cb≥0且cb−ca≥0x=2cb−ca≥1x=3ca−cb≥0x=4ca−cb≥1x=5cb−ca≥0
差分约束即可。注意此题有长链卡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;
}
总结
把不等关系列出来,差分约束连边跑单源最长路即可。