Loading

POJ 3259 Wormholes

传送门

AcWing 904 虫洞

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;
typedef long long ll;
typedef pair<int, int> p;
const int inf(0x3f3f3f3f);
const int maxn(5e2 + 10);
const int maxm(1e4 + 10);
bool vis[maxn];
int ecnt, head[maxn], cnt[maxn], dis[maxn];

struct edge {
    int to, wt, nxt;
} edges[maxm];

template<typename T>
inline const T read()
{
    T x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - '0';
        ch = getchar();
    }
    return x * f;
}

template<typename T>
inline void write(T x, bool ln)
{
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10, false);
    putchar(x % 10 + '0');
    if (ln) putchar(10);
}

void addEdge(int u, int v, int w)
{
    edges[ecnt].to = v;
    edges[ecnt].wt = w;
    edges[ecnt].nxt = head[u];
    head[u] = ecnt++;
}

bool spfa(int n)
{
    vis[0] = true;
    dis[0] = 0;
    queue<int> q;
    q.push(0);
    while (not q.empty()) {
        int u = q.front();
        q.pop();
        vis[u] = false;
        for (int i = head[u]; compl i; i = edges[i].nxt) {
            int v = edges[i].to, w = edges[i].wt;
            if (dis[v] > dis[u] + w) {
                dis[v] = dis[u] + w;
                if (not vis[v]) {
                    vis[v] = true;
                    q.push(v);
                    cnt[v] = cnt[u] + 1;
                    if (cnt[v] >= n + 1) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("input.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    int t = read<int>();
    while (t--) {
        ecnt = 0;
        memset(head, -1, sizeof head);
        memset(vis, false, sizeof vis);
        memset(cnt, 0, sizeof cnt);
        memset(dis, 0x3f, sizeof dis);
        int n = read<int>(), m = read<int>(), w = read<int>();
        while (m--) {
            int u = read<int>(), v = read<int>(), w = read<int>();
            addEdge(u, v, w);
            addEdge(v, u, w);
        }
        while (w--) {
            int u = read<int>(), v = read<int>(), w = read<int>();
            addEdge(v, u, -w);
        }
        for (int i = 1; i <= n; ++i) {
            addEdge(0, i, 0);
        }
        printf("%s\n", spfa(n) ? "YES" : "NO");
    }
    return 0;
}
posted @ 2020-10-22 11:54  SDUWH_2U  阅读(53)  评论(0编辑  收藏  举报