1 #include <set> 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 using namespace std; 6 class Egalitarianism 7 { 8 public: 9 void DFS(vector<string> &v,int p,char flag[]) 10 { 11 int i,j; 12 for (i=0;i<v.size();i++) 13 { 14 if (v[p][i]=='Y') 15 { 16 if (flag[i]==0) 17 { 18 flag[i]=1; 19 DFS(v,i,flag); 20 } 21 } 22 } 23 } 24 bool isLiantong(vector <string> v) 25 { 26 char flag[50]; 27 int i,j; 28 memset(flag,0,50); 29 flag[0]=1; 30 DFS(v,0,flag); 31 for (i=0;i<v.size();i++) 32 { 33 if (flag[i]==0) 34 { 35 return false; 36 } 37 } 38 return true; 39 } 40 int dst[50][50]; 41 void initdst(vector <string> &v) 42 { 43 int i,j; 44 for (i=0;i<v.size();i++) 45 { 46 for (j=0;j<v.size();j++) 47 { 48 if (i==j) 49 { 50 dst[i][i]=0; 51 } 52 else if (v[i][j]=='Y') 53 { 54 dst[i][j]=1; 55 } 56 else 57 { 58 dst[i][j]=1000; 59 } 60 } 61 } 62 } 63 int mindst(int n) 64 { 65 int i,j,k; 66 for (k=0;k<n;k++) 67 { 68 for (i=0;i<n;i++) 69 { 70 for (j=0;j<n;j++) 71 { 72 if (dst[i][k]+dst[k][j]<dst[i][j]) 73 { 74 dst[i][j]=dst[i][k]+dst[k][j]; 75 } 76 } 77 } 78 } 79 int re=1; 80 for (i=0;i<n;i++) 81 { 82 for (j=0;j<n;j++) 83 { 84 if (dst[i][j]>re&&dst[i][j]<1000) 85 { 86 re=dst[i][j]; 87 } 88 } 89 } 90 return re; 91 } 92 int maxDifference(vector <string> isFriend, int d) 93 { 94 if (isLiantong(isFriend)==false) 95 { 96 return -1; 97 } 98 if (d==0) 99 { 100 return 0; 101 } 102 initdst(isFriend); 103 return d*mindst(isFriend.size()); 104 } 105 }; 106 107 108 int main() 109 { 110 Egalitarianism sol; 111 vector<string> v; 112 v.push_back("NYYY"); 113 v.push_back("YNYY"); 114 v.push_back("YYNY"); 115 v.push_back("YYYN"); 116 117 cout<<sol.maxDifference(v,777)<<endl; 118 }