BZOJ2330 SCOI2011糖果

复习了一波差分约束。

http://blog.csdn.net/my_sunshine26/article/details/72849441

构图方式记住就好。

本题要倒序插入否则会被卡。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e5+10;
 4 struct node{
 5     int to,nex,w;
 6 }e[N<<2];
 7 int head[N],n,k,cnt,v[N],d[N],in[N];
 8 long long ans;queue<int>q;
 9 void add(int x,int y,int w)
10 {
11     e[++cnt].to=y;e[cnt].nex=head[x];head[x]=cnt;e[cnt].w=w;
12 }
13 bool spfa()
14 {
15     q.push(0);v[0]=1;d[0]=0;in[0]=1;
16     while(!q.empty())
17     {
18         int x=q.front();q.pop();v[x]=0;
19         for(int i=head[x];i;i=e[i].nex)
20         {
21             int y=e[i].to;
22             if(e[i].w+d[x]<=d[y])continue;
23             d[y]=d[x]+e[i].w;in[y]++;
24             if(in[y]>=n)return 0;
25             if(!v[y])
26             {
27                 q.push(y);v[y]=1;
28             }
29         }
30     }
31     return 1;
32 }
33 int main()
34 {
35     scanf("%d%d",&n,&k);
36     for(int i=1;i<=k;++i)
37     {
38         int x,a,b;
39         scanf("%d%d%d",&x,&a,&b);
40         if(x==1)add(a,b,0),add(b,a,0);
41         else if(x==2)add(a,b,1);
42         else if(x==3)add(b,a,0);
43         else if(x==4)add(b,a,1);
44         else add(a,b,0);
45     }
46     for(int i=n;i;--i)add(0,i,1);
47     if(!spfa())puts("-1");
48     else{
49         for(int i=1;i<=n;++i)ans+=d[i];
50         printf("%lld\n",ans);    
51     }
52     return 0;
53 }

 

posted @ 2018-03-20 21:25  大奕哥&VANE  阅读(162)  评论(0编辑  收藏  举报