1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| #include <bits/stdc++.h> using namespace std;
typedef long long ll; #define rep(i,a,n) for (ll i=a;i<(ll)n;i++) #define per(i,a,n) for (ll i=n;i-->(ll)a;)
ll read(){ll r;scanf("%lld",&r);return r;}
template<typename T, T INF> class MinCostFlow{ public: struct Edge { int u; int v; T cap; T cost; }; int n ; vector<Edge> e; int eidx = 0; vector<vector<pair<int,int> > > u2ve; vector<T> dis; vector<int> pre;
MinCostFlow(int n):n(n){ u2ve.resize(n); } void edge(int u,int v,T cap,T cost) { u2ve[u].push_back({v,e.size()}); e.push_back(Edge{u,v,cap,cost}); u2ve[v].push_back({u,e.size()}); e.push_back(Edge{v,u,0,-cost}); } bool spfa(int s,int t) { queue<int> q; vector<bool> in_queue(n,false); pre = vector<int>(n,-1); dis = vector<T>(n,INF); in_queue[s] = true; dis[s] = 0; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); in_queue[u] = false; for(auto [v,ei]:u2ve[u]){ if(e[ei].cap && dis[v] > dis[u] + e[ei].cost) { dis[v] = dis[u] + e[ei].cost; pre[v] = ei; if(!in_queue[v]) { q.push(v); in_queue[v]=true; } } } } return dis[t] != INF and dis[t] < 0; }
pair<T,T> flow(int s,int t) { T flow = 0; T mincost = 0; while(spfa(s,t)) { T minflow = INF; for(int ei=pre[t];ei!=-1;ei=pre[e[ei].u]){ if(e[ei].cap < minflow) minflow = e[ei].cap; } flow += minflow; for(int ei=pre[t];ei!=-1;ei=pre[e[ei].u]) { e[ei].cap -= minflow; e[ei^1].cap += minflow; } mincost += dis[t] * minflow; } return {mincost,flow}; } pair<T,T> getEdgeFlowCap(int edgeid){ assert(edgeid*2 < (int)e.size()); return {e[edgeid*2+1].cap, e[edgeid*2].cap+e[edgeid*2+1].cap }; } };
int main(){ const ll INF = 0x3f3f3f3f;
int n=read(); int m=read(); vector<int> du(n); vector<int> edgecap(m); const int S=n; const int T=S+1; MinCostFlow <ll,0x3f3f3f3f3f3f3f3f>g(T+1); rep(i,0,m){ int u=read()-1; int v=read()-1; int cap=edgecap[i]=read(); int cost=read(); if(cap&1){ du[u]--; du[v]++; } g.edge(u,v,cap/2,cost*2); } if(du[0]&1) { du[0]--; du[n-1]++; } rep(u,0,n) if(du[u]&1){ printf("Impossible\n"); return 0; } const ll off=-30000; g.edge(S ,0,INF,0); g.edge(n-1,T,INF,0); rep(u,0,n){ if(du[u] >= 0) g.edge(S,u, du[u]/2,off); else g.edge(u,T,-du[u]/2,off); } g.flow(S,T); rep(eid,m+2,m+2+n) { auto [flow,cap] = g.getEdgeFlowCap(eid); if(flow != cap){ printf("Impossible\n"); return 0; } } printf("Possible\n"); rep(eid,0,m) printf("%lld ",g.getEdgeFlowCap(eid).first*2+(edgecap[eid]&1)); return 0; }
|