Solution
首先,如果树边不是最小的,那么就不会有边权小的边了,所以这棵树是最小生成树,跑一边,把所有树边连起来,然后跑 遍最短路(我选了 Dijkstra,也可以选其他的),然后判断得到的距离是否与 一样,如果一样是 Yes,否则是 No。
Code
code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef char ch;
typedef string str;
typedef double db;
typedef __int128 i128;
const ll inf=9e18,maxn=3e3+1;
const i128 Inf=1e35;
ll n,a[maxn][maxn],m,cnt2;
struct node
{
ll u,v,w;
bool operator<(node e) const
{
return w<e.w;
}
}E[maxn*maxn];
ll fa[maxn];
ll find(ll x)
{
if(fa[x]==x) return x;
fa[x]=find(fa[x]);
return fa[x];
}
struct edge
{
ll to,nxt,w;
}e[maxn*2];
ll head[maxn],cnt;
void add(ll u,ll v,ll w)
{
e[++cnt].to=v;
e[cnt].w=w;
e[cnt].nxt=head[u];
head[u]=cnt;
return;
}
void kruscal()
{
for(int i=1;i<=n;i++) fa[i]=i;
sort(E+1,E+1+m);
for(int i=1,j=0;j<n-1;i++)
{
ll u=E[i].u,v=E[i].v,w=E[i].w,faa=find(u),fab=find(v);
if(faa!=fab)
{
fa[faa]=fab;
add(u,v,w),add(v,u,w);
j++;
}
}
}
struct node2
{
ll to,w;
bool operator <(node2 a) const
{
return w>a.w;
}
};
ll dis[maxn][maxn];
bool vis[maxn];
priority_queue<node2> pq;
void init(ll s)
{
memset(dis[s],0x3f,sizeof(dis[s]));
memset(vis,0,sizeof(vis));
dis[s][s]=0;
return;
}
void dijkstra(ll s)
{
init(s);
node2 a={s,0};
pq.push(a);
while(pq.empty()==0)
{
node2 tp=pq.top();
pq.pop();
if(vis[tp.to]) continue;
vis[tp.to]=1;
for(int i=head[tp.to];i;i=e[i].nxt)
{
ll v=e[i].to,w=e[i].w;
if(dis[s][v]>dis[s][tp.to]+w)
{
dis[s][v]=dis[s][tp.to]+w;
node2 nd={v,dis[s][v]};
pq.push(nd);
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
m=n*(n-1)/2;
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++) cin>>a[i][j],E[++cnt2].u=i,E[cnt2].v=j,E[cnt2].w=a[i][j];
}
kruscal();
for(int i=1;i<=n;i++) dijkstra(i);
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(a[i][j]!=dis[i][j])
{
cout<<"No";
return 0;
}
}
}
cout<<"Yes";
}