我们首先建图,然后对其进行SPFA差分约束判断负权回路,注意开始将点全放入队列。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<climits>
#include<string>
#include<cstdlib>
#include<set>
#include<stack>
#include<map>
#include<bitset>
#include<ctime>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline ll read()
{
char k=0;char ls;ls=getchar();for(;ls<'0'||ls>'9';k=ls,ls=getchar());
ll x=0;for(;ls>='0'&&ls<='9';ls=getchar())x=x*10+ls-'0';
if(k=='-')x=0-x;return x;
}
ll n,m,k,t;
struct E
{
ll edge;
ll zhi;
ll s;
}e[100000];
ll last[10000];
ll w;
ll dis[10000];
ll vis[10000];
ll ti[10000];
ll pan[10000];
ll spfa()
{
queue<ll>q;
for(int i=1;i<=n+m;++i)
{
q.push(i);
pan[i]=1;
}
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
memset(ti,0,sizeof(ti));
while(!q.empty())
{
ll x=q.front();q.pop();pan[x]=0;
for(ll j=last[x];j;j=e[j].zhi)
{
ll d=e[j].edge;
if(dis[d]>dis[x]+e[j].s)
{
dis[d]=dis[x]+e[j].s;
if(pan[d]==0)
{
pan[d]=1;
q.push(d);
++ti[d];
if(ti[d]>n+m)return 0;
}
}
}
}
return 1;
}
int main()
{
//freopen("matrix.in","r",stdin);
//freopen("matrix.out","w",stdout);
t=read();
while(t--)
{
n=read(),m=read(),k=read();
memset(last,0,sizeof(last));
w=0;
for(int i=1;i<=k;++i)
{
ll a1=read(),b1=read(),c1=read();
e[++w].edge=a1;
e[w].s=c1;
e[w].zhi=last[n+b1];
last[n+b1]=w;
e[++w].edge=n+b1;
e[w].s=-c1;
e[w].zhi=last[a1];
last[a1]=w;
}
if(spfa())cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
//fclose(stdin);
//fclose(stdout);
return 0;
}