hdu floyd 逆向理解

Graph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 2046    Accepted Submission(s): 1024


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

题意:一张有向图,给出各点之间的最短长度 如果该图存在 求出最少的边;

分析:由题意知,该图为有向图 ,且给出的是各点的最短路径 则一定不存在 map[i][j]>map[i][k]+map[k][j]的情况 ,若存在这样的情况 则该图不存在 输出impossible;当该图存在的时候,最多存在n*(n-1)条路径,当存在map[i][j]=map[i][k]+map[k][j]时 map[i][j]这条边可以删去。

PS:对一张图求最短路径的时候 只需迭代一个点即可,即:当i->j=i->f->g->h->j时,一定存在一个点 使得i->j=i->g->j  只需迭代一个点 即可,本题中将 k 放在内层 ,也就是在正向floyd的最外层控制变量,

code:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int t,n,map[1000][1000],ans;
int floy()
{
    int k,i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        for(k=0;k<n;k++)
    {
        if(i!=j&& i!=k&& j!=k)
        {
            if( map[i][j]==map[i][k]+map[k][j])//该边可以省略
            {
                ans--;
                break;
            }
            if(map[i][j]>map[i][k]+map[k][j])//不存在这种情况
                return 0;
        }
    }
    return 1;
}
int main()
{
    int i,j,tt=1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        memset(map,0,sizeof(map));
        for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&map[i][j]);
        ans=n*(n-1);

        int flag=floy();
        printf("Case %d: ",tt++);
        if(flag)
            printf("%d\n",ans);
        else
            printf("impossible\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值