Question: Give You A Distance matrix of a certain number and ask if this matrix is valid.
Solution: Use the tree property for prime and EDGE connection to generate the Minimum Spanning Tree. Finally, check whether the minimum spanning tree is consistent with the given one.
Solution code:
1 // file name: D. CPP 2 // Author: darkdream 3 // created time: monday, September 29, 2014, 45 minutes, 45 seconds, 4 5 # include <vector> 6 # include <list> 7 # include <map> 8 # include <set> 9 # include <deque> 10 # include <stack> 11 # include <bitset> 12 # include <algorithm> 13 # include <functional> 14 # include <numeric> 15 # include <utility> 16 # include <sstream> 17 # include <iostream> 18 # include <iomanip> 19 # include <cstdio> 20 # include <Cmath> 21 # include <cstdlib> 22 # include <cstring> 23 # include <ctime> 24 # define ll long 25 # define maxn 2010 26 using namespace STD; 27 int N; 28 int MI [maxn]; 29 vector <int> MP [2010]; 30 int NMP [maxn] [maxn]; 31 int pre [maxn]; 32 bool vis [maxn]; 33 34 long Dep [maxn]; 35 void DFS (INT la, int zla, int dis) 36 {37 Dep [la] = DIS; 38 int Len = MP [la]. size (); 39 for (INT I = 0; I <Len; I ++) 40 {41 int Ne = MP [la] [I]; 42 if (ne! = Zla) 43 {44 DFS (ne, La, DIS + NMP [la] [NE]); 45} 46} 47} 48 void prime () 49 {50 for (INT I = 1; I <= N; I ++) {51 Dep [I] = 2e9; 52 vis [I] = 0; 53} 54 Dep [1] = 0; 55 while (1) 56 {57 int v =-1; 58 for (INT I = 1; I <= N; I ++) 59 {60 if (! Vis [I] & (V =-1 | Dep [I] <Dep [v]) 61 V = I; 62} 63 If (V =-1) 64 break; 65 vis [v] = 1; 66 for (INT I = 1; I <= N; I ++) 67 {68 if (! Vis [I] & NMP [v] [I] <Dep [I]) 69 {70 Dep [I] = NMP [pre [I] = V] [I]; 71} 72} 73} 74} 75 int main () {76 scanf ("% d", & N); 77 int sum = 0; 78 int OK = 0; 79 for (INT I = 1; I <= N; I ++) 80 {81 For (Int J = 1; j <= N; j ++) 82 {83 scanf ("% d", & NMP [I] [J]); 84} 85} 86 for (INT I = 1; I <= N; I ++) 87 {88 for (Int J = 1; j <= N; j ++) 89 {90 if (I! = J & NMP [I] [J] = 0) 91 OK = 1; 92 If (NMP [I] [J]! = NMP [J] [I]) 93 OK = 1; 94} 95} 96 If (OK) 97 {98 puts ("no"); 99 return 0; 100} 101 prime (); 102 for (INT I = 2; I <= N; I ++) 103 {104 MP [I]. push_back (pre[ I]); 105 MP [pre [I]. push_back (I); 106 // printf ("% d \ n", I, pre [I]); 107} 108 For (INT I = 1; I <= N; I ++) 109 {110 DFS (I, 111);/* For (Int J = 1; j <= N; j ++) 112 printf ("% LLD", DEP [J]); 113 printf ("\ n"); */114 for (Int J = 1; j <= N; j ++) 115 {116 If (DEP [J ]! = NMP [I] [J]) 117 {118 119 puts ("no"); 120 return 0; 121} 122} 123} 124 puts ("yes "); 125 return 0; 126}
View code
Codeforces 472 (#270) D design Tutorial: inverse the problem