BZOJ1202 Cunning Merchant (Floyd)

topic analysis

Taking a look at the meaning of the question, I found that FLOYD can do it, in fact, it is to judge whether the relationship of side addition is satisfied.
It should be noted that there may be such data,
3 2
1 2 10
3 3 -15
is also true, that is to say, when the edge does not meet the judgment conditions, it can be considered to add some edges.
In other words, it is only false when it is found that the sum of the two sides is not equal to the third side.
This question can also be done with weighted and searched sets.
At first glance, the data range is only 100, of course, use Floyd to do it!

Code overview

#include<bits/stdc++.h>
using namespace std;
const int nmax = 105;
const int INF = 0x3f3f3f3f;
int w[nmax][nmax];
int t,n,m;
bool floyd(){
    for(int k = 0;k<=n;++k){
        for(int i = 0;i<=n;++i){
            for(int j = 0;j<=n;++j){
                if(w[i][k] != INF && w[k][j] != INF && w[i][j] != INF){
                    if(w[i][j] != w[i][k] + w[k][j]) return false;
                }else if(w[i][k] != INF && w[k][j] != INF){
                    w[i][j] = w[i][k] + w[k][j];
                }else if(w[i][k] != INF && w[i][j] != INF){
                    w[k][j] = w[i][j] - w[i][k];
                }else if(w[k][j] != INF && w[i][j] != INF){
                    w[i][k] = w[i][j] - w[k][j];
                }
            }
        }
    }
    return true;
}
int main(){
    scanf("%d",&t);
    while(t--){
        memset(w,INF,sizeof w);
        scanf("%d %d",&n,&m);
        int u,v,ww;
        for(int i = 0;i<m;++i){
            scanf("%d %d %d",&u,&v,&ww);
            w[u-1][v] = ww;
        }
        printf("%s\n",floyd()?"true":"false");
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730027&siteId=291194637