判负环(Bellmanford Spfa)

  • Bellmanford
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x3f3f3f
#define cio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N = 5010;

int cnt;
int flag;
int n, m;
int dis[N];
struct node
{
    int u, v, w;
}s[N*100];
int bellmanford()
{
    memset(dis,INF,sizeof(dis));
    dis[1]  = 0;
    int u, v, w;
    for(int i = 1; i < n; i++) {
        int po = 0;
        for(int j = 0; j < cnt; j++) {
            u = s[j].u; v = s[j].v; w = s[j].w;
            if(dis[v]>dis[u]+w) {
                dis[v] = dis[u]+w;
                po = 1;
            }
        }
        if(!po) return 0;
    }
    for(int i = 0; i < cnt; i++) {
        u = s[i].u; v = s[i].v; w = s[i].w;
        if(dis[v]>dis[u]+w) {
            return 1;
        }
    }
    return 0;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--) {
        cnt = 0;
        scanf("%d %d", &n, &m);
        int a, b, c;
        for(int i = 0; i < m; i++) {
            scanf("%d %d %d", &a, &b, &c);
            s[cnt].u = a; s[cnt].v = b; s[cnt].w = c;
            cnt++;
            s[cnt].u = b; s[cnt].v = a; s[cnt].w = c;
            cnt++;
        }
        if(bellmanford()) {
            puts("YES");
        }else{
            puts("NO");
        }
    }
    return 0;
}
  • SPFA
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define pi acos(-1)
#define mod 1000000007
#define ll long long
#define ull unsigned long long
#define mem(a) memset(a,0,sizeof(a))
#define cio ios::sync_with_stdio(false);

const int N = 5e5+10;
int n, m;
int s, cost;
int cnt;
int cot[500];
int vis[500];
int dis[500];
int head[500];

struct ed
{
	int to, ne;
	int w;
}e[50050];

void add(int u, int v, double w)
{
	e[cnt].to = v;
	e[cnt].ne = head[u];
	e[cnt].w = w;
	head[u] = cnt++;
}

bool spfa(int s, int cost) 
{
	memset(dis,0,sizeof(dis));
	memset(vis,0,sizeof(vis));
	dis[s] = cost;
	queue<int>que;
	cot[s]++;
	que.push(s);
	while(!que.empty()) {
		int x = que.front(); que.pop();
		vis[x] = 0;
		for(int i = head[x]; i+1; i = e[i].ne) {
			int y = e[i].to;
			double w = dis[x]+e[i].w;  // 根据条件更改
			if(dis[y]<w) {
				dis[y] = w;
				if(!vis[y]) {
					vis[y] = 1;
					que.push(y);
				}
				cot[y]++;
				if(cot[y]>=n) return 1;
			}
		}
	}
	return 0;
}

int main()
{
	cio;
	int t = 1;
	while(cin >> n >> m >> s >> cost) {
		cnt = 0;
		memset(cot,0,sizeof(cot));
		memset(head,-1,sizeof(head));
		int a, b, c;
		while(m--) {
			cin >> a >> b >> c;
			add(a,b,c);
		}
		cout << "Case " << t++ << ": ";
		if(spfa(s, cost)) {
			cout << "Yes" << endl;
		}else {
			cout << "No" << endl;
		}
	}	
	return 0;
}

你可能感兴趣的:(模板)