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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
| #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int>pii;
const int maxn=2e5+10,inf=0x3f3f3f3f,mod=1000000007; ll gcd(ll a,ll b) { if(a<b) swap(a,b); ll r; while((r=a%b)){ a=b; b=r; } return b; } ll lcm(ll a,ll b) { return (a*b)/gcd(a,b); } map<int,int>mp; struct MCMF { struct Edge { int from, to, cap, flow, cost; Edge(int u, int v, int c, int f, int w) : from(u), to(v), cap(c), flow(f), cost(w) {} }; int n, m; vector<Edge> edges; vector<int> G[maxn]; int inq[maxn]; int d[maxn]; int p[maxn]; int a[maxn]; void init(int n) { this->n = n; for (int i = 0; i <= n; i++) G[i].clear(); edges.clear(); } void AddEdge(int from, int to, int cap, int cost) {
edges.push_back(Edge(from, to, cap, 0, cost)); edges.push_back(Edge(to, from, 0, 0, -cost)); m = edges.size(); G[from].push_back(m - 2); G[to].push_back(m - 1); } bool BellmanFord(int s, int t, int& flow, ll& cost) { for (int i = 0; i < n; i++) d[i] = inf; memset(inq, 0, sizeof(inq)); d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = inf; queue<int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = 0; for (int i = 0; i < G[u].size(); i++) { Edge& e = edges[G[u][i]]; if (e.cap > e.flow && d[e.to] > d[u] + e.cost) { d[e.to] = d[u] + e.cost; p[e.to] = G[u][i]; a[e.to] = min(a[u], e.cap - e.flow); if (!inq[e.to]) { q.push(e.to); inq[e.to] = 1; } } } }
if (d[t] == inf) return false; flow += a[t]; cost += (ll)d[t] * (ll)a[t]; mp[d[t]*a[t]]+=a[t]; for (int u = t; u != s; u = edges[p[u]].from) { edges[p[u]].flow += a[t]; edges[p[u] ^ 1].flow -= a[t]; } return true; } int MincostMaxflow(int s, int t, ll& cost) { int flow = 0; cost = 0; while(BellmanFord(s, t, flow, cost)); return flow; } } mm; int cost[maxn]; signed main() {
#ifdef DEBUG freopen("input.in", "r", stdin); #endif ll n,m,u,v,w,c,q; while(~scanf("%lld%lld",&n,&m)) { mm.init(n+10); mp.clear(); for(int i=1;i<=m;i++) { scanf("%lld%lld%lld",&u,&v,&cost[i]);
mm.AddEdge(u,v,1,cost[i]); } ll tot=0,mf=mm.MincostMaxflow(1,n,tot); scanf("%lld",&q);
while(q--) { scanf("%lld%lld",&u,&v);
if(mf*u<v) puts("NaN"); else{ ll now=0,x=0,y=v; for(auto &i:mp) {
if(v>i.second*u) { v-=i.second*u; x+=i.first*u; } else{ x+=i.first*v/i.second; break; } } ll g=gcd(x,y); printf("%lld/%lld\n",x/g,y/g); } } } return 0; }
|