Codeforces 500B - New Year Permutation (思维)

题意

要得到尽量从小到大排列的序列,但是只有mp[i][j] = 1的时候才能交换两个位置。问能得到的最小序列。

思路

显然应该把小的尽量往前换,我是先对图跑一遍Floyd,然后对每个位置从小到大扫描一遍,能换就换。hcbbt巨巨用了并查集,时间比我少一半Orz。

代码

  
  
  
  
  1. #include <cstdio>
  2. #include <stack>
  3. #include <set>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <queue>
  8. #include <functional>
  9. #include <cstring>
  10. #include <algorithm>
  11. #include <cctype>
  12. #include <string>
  13. #include <map>
  14. #include <iomanip>
  15. #include <cmath>
  16. #define LL long long
  17. #define ULL unsigned long long
  18. #define SZ(x) (int)x.size()
  19. #define Lowbit(x) ((x) & (-x))
  20. #define MP(a, b) make_pair(a, b)
  21. #define MS(arr, num) memset(arr, num, sizeof(arr))
  22. #define PB push_back
  23. #define F first
  24. #define S second
  25. #define ROP freopen("input.txt", "r", stdin);
  26. #define MID(a, b) (a + ((b - a) >> 1))
  27. #define LC rt << 1, l, mid
  28. #define RC rt << 1|1, mid + 1, r
  29. #define LRT rt << 1
  30. #define RRT rt << 1|1
  31. #define BitCount(x) __builtin_popcount(x)
  32. #define BitCountll(x) __builtin_popcountll(x)
  33. #define LeftPos(x) 32 - __builtin_clz(x) - 1
  34. #define LeftPosll(x) 64 - __builtin_clzll(x) - 1
  35. const double PI = acos(-1.0);
  36. const int INF = 0x3f3f3f3f;
  37. using namespace std;
  38. const double eps = 1e-8;
  39. const int MAXN = 300 + 10;
  40. const int MOD = 1000007;
  41. const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
  42. typedef pair<int, int> pii;
  43. typedef vector<int>::iterator viti;
  44. typedef vector<pii>::iterator vitii;
  45. int mp[MAXN][MAXN];
  46. int pos[MAXN], val[MAXN], n;
  47. void Floyd()
  48. {
  49. for (int k = 1; k <= n; k++)
  50. for (int i = 1; i <= n; i++)
  51. for (int j = 1; j <= n; j++)
  52. if (mp[i][j] == 0) mp[i][j] = mp[i][k] & mp[k][j];
  53. }
  54. int main()
  55. {
  56. //ROP;
  57. int i, j;
  58. scanf("%d", &n);
  59. for (i = 1; i <= n; i++)
  60. {
  61. int tmp;
  62. scanf("%d%*c", &tmp);
  63. pos[tmp] = i, val[i] = tmp;
  64. }
  65. for (i = 1; i <= n; i++)
  66. {
  67. for (j = 1; j <= n; j++)
  68. {
  69. char tmp;
  70. scanf("%c", &tmp);
  71. mp[i][j] = tmp - '0';
  72. }
  73. getchar();
  74. }
  75. Floyd();
  76. int conti = 1;
  77. for (i = 1; i <= n; i++)
  78. for (j = conti; j <= n; j++)
  79. {
  80. if (mp[i][pos[j]])
  81. {
  82. int oriPos = pos[j];
  83. val[oriPos] = val[i];
  84. pos[val[i]] = oriPos;
  85. val[i] = j;
  86. pos[j] = i;
  87. }
  88. }
  89. for (i = 1; i <= n; i++)
  90. {
  91. if (i == 1) printf("%d", val[i]);
  92. else printf(" %d", val[i]);
  93. }
  94. puts("");
  95. return 0;
  96. }

你可能感兴趣的:(ACM,codeforces)