Source code for submission s1035

spider.cpp

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdint.h>
  5. #include <ctype.h>
  6. #include <math.h>
  7.  
  8. #include <string>
  9. #include <vector>
  10. #include <map>
  11. #include <set>
  12. #include <algorithm>
  13.  
  14. using namespace std;
  15.  
  16. typedef pair <int, int> PII;
  17. typedef long long int LL;
  18. typedef vector <int> VI;
  19. typedef vector <LL> VLL;
  20.  
  21. #define FOR(i, a, b) for ( int i = a; i < b; ++i )
  22. #define FORD(i, a, b) for ( int i = a-1; i >= 0; --i )
  23.  
  24. #define FILL(x, v, n) for ( int _i = 0; _i < n; ++_i ) x[_i] = v;
  25.  
  26. const int MAX_V = 2001;
  27. const int MAX_E = 1000005;
  28.  
  29. struct Edge
  30. {
  31. int a, b, w;
  32. };
  33.  
  34. int uf[ MAX_V ];
  35. Edge edge[ MAX_E ];
  36.  
  37. struct UnionFind
  38. {
  39. int N, numSets;
  40. void Init ( int n )
  41. {
  42. N = n;
  43. numSets = N;
  44. FOR(i,0,N)
  45. uf[ i ] = i;
  46. }
  47.  
  48. void Union ( int i, int j )
  49. {
  50. if ( !IsSameSet( i, j ) )
  51. {
  52. --numSets;
  53. int fi = Find( i ), fj = Find( j );
  54. uf[ fi ] = uf[ fj ];
  55. }
  56. }
  57. int Find ( int i ) { return (uf[i] == i) ? i : (uf[i] = Find(uf[i]) ); }
  58. bool IsSameSet ( int i, int j ) { return Find( i ) == Find( j ); }
  59. };
  60.  
  61. bool Comp ( const Edge & a, const Edge & b )
  62. {
  63. return a.w < b.w;
  64. }
  65.  
  66. int main()
  67. {
  68. UnionFind u;
  69. int N, M, max, maxID;
  70. while ( scanf( "%d %d", &N, &M ) == 2 )
  71. {
  72. max = 0;
  73. FOR(i,0,M)
  74. {
  75. scanf( "%d %d %d", &edge[ i ].a, &edge[ i ].b, &edge[ i ].w );
  76. --edge[ i ].a;
  77. --edge[ i ].b;
  78. if ( edge[ i ].w > max )
  79. {
  80. max = edge[ i ].w;
  81. maxID = i;
  82. }
  83. }
  84. if ( M == 0 )
  85. {
  86. printf( "disconnected\n" );
  87. continue;
  88. }
  89.  
  90. edge[ maxID ].w = -edge[ maxID ].w;
  91. sort( edge, edge + M, Comp );
  92.  
  93. int res = 0;
  94. u.Init( N );
  95. FOR(i,0,M)
  96. if ( !u.IsSameSet( edge[ i ].a, edge[ i ].b ) )
  97. {
  98. u.Union( edge[ i ].a, edge[ i ].b );
  99. res += edge[ i ].w;
  100. if ( u.numSets == 1 )
  101. break;
  102. }
  103. if ( u.numSets == 1 )
  104. printf( "%d\n", res );
  105. else
  106. printf( "disconnected\n" );
  107. }
  108. return 0;
  109. }
  110.