tomography

11/10/2024

TLE

Code
// https://vjudge.net/problem/Kattis-tomography
#include <bits/stdc++.h> 
#define pb push_back
using namespace std;
const int N = 2e3+5;
const int INF = 1e9;

int n,m;
int a[N], b[N];
vector<int> adj[N];
int source, sink, cap[N][N], lvl[N];
bool vis[N];
vector<int> path;

bool bfs(){
    for (int i=source;i <= sink;i++) lvl[i] = -1;
    lvl[source] = 0;
    queue<int> q; q.push(source);
    while(!q.empty()){ 
        int u = q.front();q.pop();
        for (auto v : adj[u]) {
            if (lvl[v] == -1 && cap[u][v] > 0) {
                lvl[v] = lvl[u] + 1;
                q.push(v);
            }
        }
    }
    return (lvl[sink] != -1);
}

void findPath(int u){
    vis[u] = true;
    path.pb(u);
    if (u == sink) return;
    for (auto v : adj[u]) {
        if (lvl[v] == lvl[u] + 1 && !vis[v] && cap[u][v] > 0) {
            findPath(v);
            if (path.back() == sink) return;
        }
    }
    path.pop_back();
}

signed main() {
    ios_base::sync_with_stdio(0);cin.tie(0);

    cin >> n >> m;
    for (int i=1;i <= n;i++)
        cin >> a[i];
    for (int i=1;i <= m;i++) {
        cin >> b[n+i];
    }
    source = 0;
    sink = n + m + 1;
    int sumLeft = 0, sumRight = 0;
    for (int i=1;i <= n;i++) {
        adj[source].pb(i);
        cap[source][i] = a[i];
        sumLeft += a[i];
    }
    for (int i=n+1;i <= n+m;i++) {
        adj[i].pb(sink);
        cap[i][sink] = b[i];
        sumRight += b[i];
    }
    for (int i=1;i <= n;i++) {
        for (int j=n+1;j <= n+m;j++) {
            adj[i].pb(j);
            adj[j].pb(i);
            cap[i][j] = 1;
        }
    }
    if (sumLeft != sumRight) {
        cout << "No";
        return 0 ;
    }
    int ans = 0;
    while(bfs()) {
        path.clear();
        for (int i=source;i <= sink;i++) {
            vis[i] = false;
        }
        findPath(source);
        int minCost = INF;
        for (int i=1;i < path.size();i++) {
            int u = path[i-1];
            int v = path[i];
            minCost = min(minCost, cap[u][v]);
        }
        ans += minCost;
        for (int i=1;i < path.size();i++) {
            int u = path[i-1];
            int v = path[i];
            cap[u][v] -= minCost;
            cap[v][u] += minCost;
        }
    }
    cout << (ans == sumLeft ? "Yes" : "No");
    return 0;
}