传送门:P1993 小K的农场
本以为是道差分约束模板题,就开开心心 bfs spfa 提交一发,结果 T 了 4 个样例,非常难受。看题解区的 dalao 们都上了 dfs 版本的 spfa,本蒟蒻不会写 dfs,把 queue 改成了 stack,假装自己在写 dfs,然后就过了。(卡 bfs 真的太坑了)
#include <bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e4+4;
struct Edge
{
int to, w;
Edge() {}
Edge(int to, int w): to(to), w(w) {}
};
int n, m;
vector<Edge> g[maxn];
int dis[maxn], vis[maxn], c[maxn];
void read()
{
cin >> n >> m;
int opt, a, b, c;
for(int i = 0; i < m; ++i)
{
cin >> opt >> a >> b;
if(opt == 1)
cin >> c, g[a].push_back(Edge(b, -c));
else if(opt == 2)
cin >> c, g[b].push_back(Edge(a, c));
else
g[a].push_back(Edge(b, 0)), g[b].push_back(Edge(a, 0));
}
}
bool spfa()
{
stack<int> q;
for(int i = 1; i <= n; ++i)
{
q.push(i);
vis[i] = 1;
}
while(!q.empty())
{
int u = q.top();
q.pop();
vis[u] = 0;
for(int i = 0; i < g[u].size(); ++i)
{
int v = g[u][i].to, w = g[u][i].w;
if(dis[v] > dis[u]+w)
{
dis[v] = dis[u]+w;
if(!vis[v])
{
q.push(v);
vis[v] = 1;
if(++c[v] > n)
return false;
}
}
}
}
return true;
}
void solve()
{
if(spfa())
cout << "Yes" << endl;
else
cout << "No" << endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
read();
solve();
return 0;
}