poj 3259 Wormholes (BELLman—FOrd算法)(邻接矩阵表示)

http://poj.org/problem?id=3259

 

之前一开始 ,没做出来,搁置了好几天才看见bug所在。所以今天a掉了 ,把代码贴出来,这个使用邻接矩阵表示的 ,下一篇用邻接表可以提高效率。

#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
const int INF=600;
int G[INF][INF];
int inq[INF];
int res[INF];
int dict[INF];
int n,m,w;

bool spfa(int x)
{
    queue<int>cnt;
    memset(dict,0,sizeof(dict));
    cnt.push(x);
    memset(res,0x1f,sizeof(res));
    memset(inq,0,sizeof(inq));
    res[x]=0;
    dict[x]++;
    while(!cnt.empty())
    {
        int cur=cnt.front();
        cnt.pop();
        inq[cur]=0;
        for(int i=1; i<=n; i++)
        {
            if(res[i]>res[cur]+G[cur][i])
            {
                res[i]=res[cur]+G[cur][i];
                if(!inq[i])
                {
                    cnt.push(i);
                    inq[i]=1;
                    if(++dict[i]>=n)
                        return 1;
                }
            }
        }
    }
    return 0;
}

int main()
{
    int s,e,t;
    int T;
    cin>>T;
    while(T--)
    {
        cin>>n>>m>>w;
        memset(G,0x1f,sizeof(G));
        int k;
        for(int i=0; i<m; i++)
        {
            cin>>s>>e>>t;
            G[s][e]=G[e][s]= G[e][s]>t? t:G[s][e];
            k=s;
        }
        for(int j=0; j<w; j++)
        {
            cin>>s>>e>>t;
            G[s][e]=G[s][e]>-t?-t : G[s][e];

        }
        printf("%s\n",spfa(1)?"YES":"NO");
    }
    return 0;

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值