洛谷P3275 [SCOI2011]糖果

差分约束大坑题

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<algorithm>
 4 #include<cstring>
 5 #define re register int
 6 #define ll long long
 7 #define MAXN 100000+10
 8 using namespace std;
 9 int n,m;
10 int b[MAXN];
11 ll d[MAXN];
12 int fst[MAXN],nxt[3*MAXN],to[3*MAXN],vl[3*MAXN],cnt;
13 char ss[1<<17],*A=ss,*B=ss;
14 inline char gc(){if(A==B){B=(A=ss)+fread(ss,1,1<<17,stdin);if(A==B)return EOF;}return*A++;}
15 template<class T>inline void read(T&x){
16     char c;re y=1;while(c=gc(),c<48||57<c)if(c=='-')y=-1;x=c^48;
17     while(c=gc(),47<c&&c<58)x=(x<<1)+(x<<3)+(c^48);x*=y;
18 }
19 inline void ins(int x,int y,int w){
20     nxt[++cnt]=fst[x],fst[x]=cnt,to[cnt]=y,vl[cnt]=w;
21 }
22 inline int spfa(int x){
23     b[x]=1;
24     for(re e=fst[x];e;e=nxt[e]){
25         re y=to[e],w=vl[e];
26         if(d[y]>d[x]+w){
27             d[y]=d[x]+w;
28             if(b[y]||!spfa(y))return 0;
29         }
30     }
31     b[x]=0;
32     return 1;
33 }
34 int main()
35 {
36 //    freopen("data.in","r",stdin);
37     read(n),read(m);
38     for(re i=n;i>=1;i--){
39         ins(0,i,-1);    
40     }
41     int k,x,y;
42     for(re i=1;i<=m;i++){
43         read(k),read(x),read(y);
44         if(k%2==0&&x==y){
45             printf("-1\n");
46             return 0;    
47         }
48         switch(k){
49             case 1:ins(x,y,0),ins(y,x,0);break;
50 /*<*/        case 2:ins(x,y,-1);break;
51 /*>=*/        case 3:ins(y,x,0);break;
52 /*>*/        case 4:ins(y,x,-1);break;
53 /*<=*/        case 5:ins(x,y,0);
54         }    
55     }
56 //    for(int i=1;i<=n;i++){
57 //        printf("%d:",i);
58 //        for(int j=fst[i];j;j=nxt[j]){
59 //            printf("%d ",to[j]);
60 //        }
61 //        printf("\n");
62 //    }
63     ll ans=0;
64     if(spfa(0)){
65         for(re i=1;i<=n;i++)
66             ans-=d[i];    
67         printf("%lld\n",ans);
68     }
69     else{
70         printf("-1\n");    
71     }
72     return 0;    
73 }
View Code

另外用tarjan缩一下点就不会卡常了,然而比较难写

posted @ 2018-01-11 23:06  white_hat_hacker  阅读(170)  评论(0编辑  收藏  举报