[BZOJ2330][SCOI2011]糖果

原题地址

差分约束系统.

AC code:

#include 
#include 
using namespace std;
typedef long long ll;
const int N=1000010;
const int INF=1<<28;
ll   ans;
int  n,k,S,cnt;
int  head[N],maxw[N],tim[N];
bool inq[N];

struct Edge{
    int v,w,next;

    Edge() {}
    Edge(int v,int w,int next):v(v),w(w),next(next) {}
}E[N];

void addedge(int u,int v,int w){
    E[++cnt]=Edge(v,w,head[u]);
    head[u]=cnt;
}

void SPFA(){
    queue<int> Q;
    maxw[S]=1;
    for(int i=1;i<=n;i++) maxw[i]=-INF;
    Q.push(S);inq[S]=1;
    while(!Q.empty()){
        int x=Q.front();
        Q.pop();inq[x]=0;
        for(int i=head[x];i;i=E[i].next){
            Edge e=E[i];
            if(maxw[x]+e.w<=maxw[e.v]) continue;
            if(++tim[e.v]>n){
                printf("-1\n");
                return ;
            }
            maxw[e.v]=maxw[x]+e.w;
            if(!inq[e.v]){inq[e.v]=1;Q.push(e.v);}
        }
    }
    for(int i=1;i<=n;i++) ans+=maxw[i];
    printf("%lld\n",ans);
}

int main(){
    scanf("%d%d",&n,&k);
    S=n+1;
    for(int i=n;i>=1;i--) addedge(S,i,0);
    for(int i=1;i<=k;i++){
        int x,a,b;
        scanf("%d%d%d",&x,&a,&b);
        if(x==1){addedge(a,b,0);addedge(b,a,0);}
        else if(x==2) addedge(a,b,1);
        else if(x==3) addedge(b,a,0);
        else if(x==4) addedge(b,a,1);
        else addedge(a,b,0);
    }
    SPFA();

    return 0;  
}

你可能感兴趣的:(BZOJ,图论_最短路,图论)