case | 转换不等式 | 转换不等式2 |
---|---|---|
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
#define N 100100
using namespace std ;
typedef long long ll ;
struct node
{
int to ;
int val ;
int next ;
};
node edge[N*5] ;
int head[N] ;
int hash[N] ;
int d[N] ;
int v[N] ;
int cnt ;
void init()
{
memset(head , -1 , sizeof(head)) ;
cnt = 1 ;
}
void edgeadd(int from , int to , int val)
{
edge[cnt].to = to ;
edge[cnt].val = val ;
edge[cnt].next = head[from] ;
head[from] = cnt ++ ;
}
int n , k ;
int spfa()
{
memset(d , -0x3f ,sizeof(d)) ;
queue <int> q ;
q.push(n+1) ;
d[n+1] = 0 ;
v[n+1] = 1 ;
hash[n+1]=1;
while(!q.empty())
{
int u = q.front() ;
q.pop() ;
v[u] = 0 ;
for(int i = head[u] ; i != -1 ; i = edge[i].next)
{
int to = edge[i].to ;
if(d[u] + edge[i].val > d[to])
{
d[to] = d[u] + edge[i].val ;
if(++hash[to] >=n) return 0 ;
if(!v[to])
{
v[to] = 1 ;
q.push(to) ;
}
}
}
}
return 1 ;
}
int main()
{
scanf("%d%d" , &n , &k) ;
init() ;
for(int i = 1 ; i <= k ; i++)
{
int jd ;
scanf("%d" , &jd) ;
int x , y ;
scanf("%d%d" , &x , &y) ;
if(jd==1){edgeadd(x,y,0);edgeadd(y,x,0);}
else if(jd==2){edgeadd(x,y,1);}
else if(jd==3){edgeadd(y,x,0);}
else if(jd==4){edgeadd(y,x,1);}
else if(jd==5){edgeadd(x,y,0);}
}
for(int i = n ; i >= 1 ; i--)
{
edgeadd(n+1 , i , 1) ;
}
if(spfa())
{
ll sum = 0 ;
for(int i = 1 ; i <= n ;i++)
{
sum += d[i] ;
}
printf("%lld\n" , sum) ;
}else printf("-1\n") ;
}
BZOJ 2330 [SCOI2011]糖果 差分约束spfa版
原文地址:http://blog.csdn.net/wzq_qwq/article/details/45578837