入队次数判法
#include<bits/stdc++.h>
using namespace std;
const int maxn=6010;
int n,m,o;
int h[maxn],nxt[maxn],to[maxn],w[maxn],tot;
bool v[maxn];
int dis[maxn],cnt[maxn];
void add (int x,int y,int z)
{
tot++;
to[tot]=y;
w[tot]=z;
nxt[tot]=h[x];
h[x]=tot;
}
bool spfa()
{
memset(v,0,sizeof(v));
queue<int> q;
for (int i=1;i<=n;i++)
{
q.push(i);
v[i]=true;
}
while (q.size())
{
int x=q.front();
q.pop();
v[x]=false;
for (int i=h[x];i;i=nxt[i])
{
int y=to[i];
if (dis[y]>dis[x]+w[i])
{
dis[y]=dis[x]+w[i];
if (!v[y])
{
q.push(y);
v[y]=true;
cnt[y]++;
if (cnt[y]>=n) return true;
}
}
}
}
return false;
}
int main()
{
int t;
cin >> t;
while (t--)
{
tot=0;
memset(h,0,sizeof(h));
memset(nxt,0,sizeof(nxt));
memset(to,0,sizeof(to));
memset(w,0,sizeof(w));
memset(cnt,0,sizeof(cnt));
memset(dis,0,sizeof(dis));
cin >> n >> m >> o;
for (int i=1;i<=m;i++)
{
int x,y,z;
cin >> x >> y >> z;
add(x,y,z);
add(y,x,z);
}
for (int i=1;i<=o;i++)
{
int x,y,z;
cin >> x >> y >> z;
add(x,y,-z);
}
if (spfa()) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
边数判法
#include<bits/stdc++.h>
using namespace std;
const int maxn=6010;
int n,m,o;
int h[maxn],nxt[maxn],to[maxn],w[maxn],tot;
bool v[maxn];
int dis[maxn],cnt[maxn];
void add (int x,int y,int z)
{
tot++;
to[tot]=y;
w[tot]=z;
nxt[tot]=h[x];
h[x]=tot;
}
bool spfa()
{
memset(v,0,sizeof(v));
queue<int> q;
for (int i=1;i<=n;i++)
{
q.push(i);
v[i]=true;
}
while (q.size())
{
int x=q.front();
q.pop();
v[x]=false;
for (int i=h[x];i;i=nxt[i])
{
int y=to[i];
if (dis[y]>dis[x]+w[i])
{
dis[y]=dis[x]+w[i];
cnt[y]=cnt[x]+1;
if (cnt[y]>=n) return true;
if (!v[y])
{
q.push(y);
v[y]=true;
}
}
}
}
return false;
}
int main()
{
int t;
cin >> t;
while (t--)
{
tot=0;
memset(h,0,sizeof(h));
memset(nxt,0,sizeof(nxt));
memset(to,0,sizeof(to));
memset(w,0,sizeof(w));
memset(cnt,0,sizeof(cnt));
memset(dis,0,sizeof(dis));
cin >> n >> m >> o;
for (int i=1;i<=m;i++)
{
int x,y,z;
cin >> x >> y >> z;
add(x,y,z);
add(y,x,z);
}
for (int i=1;i<=o;i++)
{
int x,y,z;
cin >> x >> y >> z;
add(x,y,-z);
}
if (spfa()) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}