F Metric Matrice

                                                               Metric Matrice


描述

Given as input a square distance matrix, where a[i][j] is the distance between point i and point j, determine if the distance matrix is "a  metric" or not.

A distance matrix a[i][j] is a metric if and only if

    1.  a[i][i] = 0

    2, a[i][j]> 0  if i != j

    3.  a[i][j] = a[j][i]

    4.  a[i][j] + a[j][k] >= a[i][k]  i ¹ j ¹ k

输入
The first line of input gives a single integer, 1 ≤ N ≤ 5, the number of test cases. Then follow, for each test case,
* Line 1: One integer, N, the rows and number of columns, 2 <= N <= 30
* Line 2..N+1: N lines, each with N space-separated integers 
(-32000 <=each integer <= 32000).
输出
Output for each test case , a single line with a single digit, which is the lowest digit of the possible facts on this list:
* 0: The matrix is a metric
* 1: The matrix is not a metric, it violates rule 1 above
* 2: The matrix is not a metric, it violates rule 2 above
* 3: The matrix is not a metric, it violates rule 3 above
* 4: The matrix is not a metric, it violates rule 4 above
样例输入
240 1 2 31 0 1 22 1 0 13 2 1 020 32 0
样例输出
03
来源
第五届河南省程序设计大赛
上传者

rihkddd

解题思路:根据四个条件按个模拟,不过要注意的是要是违反条件2和4则输出先违反的条件2

我的代码:

#include<bits/stdc++.h>
using namespace std;
int a[35][35],n;
int rule1()
{
   for(int i=0;i<n;i++)
   {
       if(a[i][i]!=0)
        return 1;
   }
   return 0;
}
int rule2()
{
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
    {
        if(i!=j)
        {
            if(a[i][j]<=0)
                return 1;
        }
    }
    return 0;
}
int rule3()
{
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
    {
        if(a[i][j]!=a[j][i])
            return 1;
    }
    return 0;
}
int rule4()
{
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
        {
            if(i==j)
                break;
            for(int k=0;k<n;k++)
            {
                if(i==k||j==k)
                    break;
                if(a[i][j]+a[j][k]<a[i][k])
                    return 1;
            }
        }
    return 0;
}
int main()
{
   int num;
   scanf("%d",&num);
   while(num--)
   {
       int i,j,b[5]={0};
       scanf("%d",&n);
       for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
           scanf("%d",&a[i][j]);
        }
       b[1]=rule1();
       b[2]=rule2();
       b[3]=rule3();
       b[4]=rule4();
       int flag=0;
       for(i=1;i<=4;i++)
       {
           if(b[i]==1)
           {
               printf("%d\n",i);
               flag=1;
               break;
           }
       }
       if(flag==0)
            printf("0\n");
   }
}





posted @ 2017-04-24 21:09  X_na  阅读(111)  评论(0)    收藏  举报