博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Restoring Road Network
阅读量:5039 次
发布时间:2019-06-12

本文共 2318 字,大约阅读时间需要 7 分钟。

Restoring Road Network

时间限制: 1 Sec  内存限制: 128 MB
In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads. The following are known about the road network:
People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.
Different roads may have had different lengths, but all the lengths were positive integers.
Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom. He thought that it represented the shortest distances between the cities along the roads in the kingdom.
Determine whether there exists a road network such that for each u and v, the integer Au,v at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v. If such a network exist, find the shortest possible total length of the roads.
Constraints
1≤N≤300
If i≠j, 1≤Ai,j=Aj,i≤109.
Ai,i=0

 

输入

Input is given from Standard Input in the following format:
N
A1,1 A1,2 … A1,N
A2,1 A2,2 … A2,N
AN,1 AN,2 … AN,N

 

输出

If there exists no network that satisfies the condition, print -1. If it exists, print the shortest possible total length of the roads.

 

样例输入

30 1 31 0 23 2 0

 

样例输出

3

 

提示

The network below satisfies the condition:

City 1 and City 2 is connected by a road of length 1.
City 2 and City 3 is connected by a road of length 2.
City 3 and City 1 is not connected by a road.

 

来源/分类

 


#include
using namespace std;long long Map[350][350];int vis[350][350]={
0}; int main(){ int n; long long ans=0; scanf("%d",&n); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++)scanf("%lld",&Map[i][j]); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { int t=1; for(int k=1;k<=n;k++) if(i!=j&&i!=k&&j!=k&&Map[i][j]>Map[i][k]+Map[k][j]) { printf("-1"); return 0; } else if(i!=j&&i!=k&&j!=k&&Map[i][j]==Map[i][k]+Map[k][j])t=0; if(t)ans+=Map[i][j]; } printf("%lld",ans/2); return 0;}
View Code

为什么这里的循环和floyd算法里的不一样,我个人认为是因为我们现在要检测每两个点之间是否是最短路状态,所以我们枚举其他点,看看是否能进行最小路径的更新工作,也就是“松弛”操作。

至于第二问,我们要想求建立这个图的最小边花费,就要尽可能的重用边,话句话说,就是如果A->B->C和A->C的路径花费一样,我们肯定选第一条路径。

又因为这样选的边是双向的,所以答案要除以2。

 

转载于:https://www.cnblogs.com/tian-luo/p/9411133.html

你可能感兴趣的文章
.net常见的一些面试题
查看>>
OGRE 源码编译方法
查看>>
上周热点回顾(10.20-10.26)
查看>>
C#正则表达式引发的CPU跑高问题以及解决方法
查看>>
云计算之路-阿里云上:“黑色30秒”走了,“黑色1秒”来了,真相也许大白了...
查看>>
APScheduler调度器
查看>>
设计模式——原型模式
查看>>
【jQuery UI 1.8 The User Interface Library for jQuery】.学习笔记.1.CSS框架和其他功能
查看>>
如何一个pdf文件拆分为若干个pdf文件
查看>>
web.xml中listener、 filter、servlet 加载顺序及其详解
查看>>
前端chrome浏览器调试总结
查看>>
获取手机验证码修改
查看>>
数据库连接
查看>>
python中数据的变量和字符串的常用使用方法
查看>>
等价类划分进阶篇
查看>>
delphi.指针.PChar
查看>>
Objective - C基础: 第四天 - 10.SEL类型的基本认识
查看>>
java 字符串转json,json转对象等等...
查看>>
极客前端部分题目收集【索引】
查看>>
第四天 selenium的安装及使用
查看>>