AcWing 1169. 糖果

思路

  • 根据不同的关系来建立不同的边
    • 1.若X=1,则建立边(u,v,0),表示两者相等.
    • 2.若X=2,则建立边(u,v,1),表示v比u大一.
    • 3.若X=3,则建立边(v,u,0),表示u大于等于v.
    • 4.若X=4,则建立边(v,u,1),表示u比v大一.
    • 5.若X=5,则建立边(u,v,0),表示u小于等于v.
  • 再用一个超级原点,和所有的点连一条从超级原点到所有边的权值为1的边,这样就能保证所有点的值都大于0
  • 然后跑一遍spfa,求出单源最长路即可,这里spfa里要用stack或者手写队列,否则直接用STL里的queue会T

代码

#include <stack>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N=1e5+5;
const int M=3e5+5;
int n,k;
int h[N];int e[M];int ne[M];int w[M];int idx;
ll dist[N];
int cnt[N];
bool st[N];
stack<int> q;

void add(int a,int b,int c){
    e[idx]=b,w[idx]=c;ne[idx]=h[a];h[a]=idx++;
}
bool SPFA(){
    memset(dist, -0x3f, sizeof dist);
    dist[0] = 0;
    q.push(0);
    st[0] = true;

    while (!q.empty())
    {
        int t = q.top();
        st[t] = false;
        q.pop();
        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] < dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                cnt[j] = cnt[t] + 1;
                if (cnt[j] >= n + 1) return false;
                if (!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }

    return true;
}
int main(){
    memset(h,-1,sizeof h);
    scanf("%d%d",&n,&k);
    while(k--){
        int x;
        scanf("%d",&x);
        int a,b;
        scanf("%d%d",&a,&b);
        if(x==1){
            add(a,b,0);
            add(b,a,0);
        }
        if(x==2){
            add(a,b,1);
        }
        if(x==3){
            add(b,a,0);
        }
        if(x==4){
            add(b,a,1);
        }
        if(x==5){
            add(a,b,0);
        }
    }
    for(int i=1;i<=n;i++){
        add(0,i,1);
    }
    if(!SPFA()){
        cout << -1;
    }else{
        ll res=0;
        for(int i=1;i<=n;i++)res+=dist[i];
        cout << res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值