考虑每一颗绿宝石向连边,把一次加看做一个点的点值加
只需要看每个环上是否恒等,bfs即可
#include<bits/stdc++.h>
using namespace std;
#define ll long long
inline int read(){
char ch=getchar();
int res=0,f=1;
while(!isdigit(ch)){if(ch=='-')f=-f;ch=getchar();}
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=getchar();
return res*f;
}
const int N=20005;
int adj[N],nxt[N<<1],to[N<<1],del[N],vis[N],cnt,val[N];
int n,m,k;
inline void addedge(int u,int v,int w){
nxt[++cnt]=adj[u],adj[u]=cnt,to[cnt]=v,val[cnt]=w;
}
inline bool bfs(int str){
queue<int> q;
vis[str]=1,q.push(str);
while(!q.empty()){
int u=q.front();q.pop();
for(int e=adj[u];e;e=nxt[e]){
int v=to[e];
if(vis[v]){
if(del[u]+del[v]==val[e])continue;
else return false;
}
del[v]=val[e]-del[u];
vis[v]=1,q.push(v);
}
}
return true;
}
int main(){
int T=read();
while(T--){
memset(adj,0,sizeof(adj)),cnt=0;
memset(vis,0,sizeof(vis));
n=read(),m=read(),k=read();
for(int i=1;i<=k;i++){
int u=read(),v=read(),w=read();
addedge(u,v+n,w),addedge(v+n,u,w);
}
bool flag=true;
for(int i=1;i<=n+m;i++){
if(!vis[i])if(!bfs(i))flag=false;
}
puts(flag?"Yes":"No");
}
}