hdu 4034 Graph 已知最短路,求图中最少边数

本文探讨了如何从给定的最短路径矩阵推导出原始图的最小边数,通过实例展示了求解过程,并指出在特定情况下无法构建相应的原始图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
Everyone knows how to calculate the shortest path in a directed graph. In fact, the opposite problem is also easy. Given the length of shortest path between each pair of vertexes, can you find the original graph?
 


 

Input
The first line is the test case number T (T ≤ 100).
First line of each case is an integer N (1 ≤ N ≤ 100), the number of vertexes.
Following N lines each contains N integers. All these integers are less than 1000000.
The jth integer of ith line is the shortest path from vertex i to j.
The ith element of ith line is always 0. Other elements are all positive.
 


 

Output
For each case, you should output “Case k: ” first, where k indicates the case number and counts from one. Then one integer, the minimum possible edge number in original graph. Output “impossible” if such graph doesn't exist.

 


 

Sample Input
  
  
3 3 0 1 1 1 0 1 1 1 0 3 0 1 3 4 0 2 7 3 0 3 0 1 4 1 0 2 4 2 0
 


 

Sample Output
  
  
Case 1: 6 Case 2: 4 Case 3: impossible

 

//

 

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=110;
int a[maxn][maxn];
int vis[maxn][maxn];
int n;
int main()
{
    int ci,pl=1;scanf("%d",&ci);
    while(ci--)
    {
        scanf("%d",&n);
        int ans=n*(n-1);
        memset(vis,0,sizeof(vis));
        int flag=1;
        for(int i=0;i<n;i++) for(int j=0;j<n;j++) scanf("%d",&a[i][j]);
        for(int k=0;k<n&&flag;k++)
        {
            for(int i=0;i<n&&flag;i++)
            {
                for(int j=0;j<n&&flag;j++)
                {
                    if(i!=j&&j!=k&&i!=k&&!vis[i][k]&&!vis[k][j]&&!vis[i][j])
                    {
                        if(a[i][j]==a[i][k]+a[k][j])
                        {
                            ans--;
                            vis[i][j]=1;
                        }
                        else if(a[i][j]>a[i][k]+a[k][j])
                        {
                            flag=0;break;
                        }
                    }
                }
            }
        }
        if(flag) printf("Case %d: %d\n",pl++,ans);
        else printf("Case %d: impossible\n",pl++);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值