Advertisement
tuki2501

assign1.cpp

Nov 12th, 2021
1,197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 605;
  5. const int A = 300;
  6.  
  7. int n, a[N][N];
  8. vector<int> adj[N];
  9. int capa[N][N], flow[N][N], level[N];
  10.  
  11. bool bfs(int s, int t) {
  12.   memset(level, 0, sizeof(level));
  13.   queue<int> q; q.push(s); level[s] = 1;
  14.   bool flag = false;
  15.   while (q.size()) {
  16.     int i = q.front(); q.pop();
  17.     if (i == t) flag = true;
  18.     for (auto &j : adj[i]) {
  19.       if (capa[i][j] - flow[i][j] >= 1 && !level[j]) {
  20.         level[j] = level[i] + 1;
  21.         q.push(j);
  22.       }
  23.     }
  24.   }
  25.   return flag;
  26. }
  27.  
  28. bool dfs(int i, int t) {
  29.   if (i == t) return true;
  30.   for (auto &j : adj[i]) {
  31.     if (capa[i][j] - flow[i][j] >= 1 && level[j] == level[i] + 1) {
  32.       flow[i][j]++;
  33.       flow[j][i]--;
  34.       if (dfs(j, t)) return true;
  35.       flow[i][j]--;
  36.       flow[j][i]++;
  37.     }
  38.   }
  39.   return false;
  40. }
  41.  
  42. bool check(int x) {
  43.   for (int i = 0; i < N; i++) {
  44.     adj[i].clear();
  45.   }
  46.   memset(capa, 0, sizeof(capa));
  47.   memset(flow, 0, sizeof(flow));
  48.   for (int i = 1; i <= n; i++)
  49.   for (int j = 1; j <= n; j++) {
  50.     if (a[i][j] <= x) {
  51.       adj[i].push_back(j + A);
  52.       adj[j + A].push_back(i);
  53.       capa[i][j + A] = 1;
  54.     }
  55.   }
  56.   for (int i = 1; i <= n; i++) {
  57.     adj[0].push_back(i);
  58.     adj[i].push_back(0);
  59.     capa[0][i] = 1;
  60.   }
  61.   for (int j = 1; j <= n; j++) {
  62.     adj[j + A].push_back(600);
  63.     adj[600].push_back(j + A);
  64.     capa[j + A][600] = 1;
  65.   }
  66.   int ans = 0;
  67.   while (bfs(0, 600)) {
  68.     while (dfs(0, 600)) ans++;
  69.   }
  70.   return (ans == n);
  71. }
  72.  
  73. int main() {
  74.   cin.tie(0)->sync_with_stdio(0);
  75.   cin >> n;
  76.   for (int i = 1; i <= n; i++)
  77.   for (int j = 1; j <= n; j++) {
  78.     cin >> a[i][j];
  79.   }
  80.   int l = 0, r = INT_MAX, ans = -1;
  81.   while (l <= r) {
  82.     int x = l + (r - l) / 2;
  83.     if (check(x)) {
  84.       ans = x;
  85.       r = x - 1;
  86.     }
  87.     else l = x + 1;
  88.   }
  89.   cout << ans << '\n';
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement