嘟嘟嘟
上下界网络流之最小流。
建图不说啦,裸的。
在有附加源\(S\)和附加汇\(T\)的图上跑完后,删除和\(S, T\)相连的边。然后因为可能流多了,所以现在应该退流,于是我们从\(t\)到\(s\)跑一遍最大流就行了。
今天总算有一道1A的题了,舒服。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 55;
const int maxe = 1e5 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, m, s, t, S, T;
char s1[2], s2[2];
struct Edge
{
int nxt, from, to, cap, flow;
}e[maxe];
int head[maxn], ecnt = -1;
void addEdge(int x, int y, int w)
{
e[++ecnt] = (Edge){head[x], x, y, w, 0};
head[x] = ecnt;
e[++ecnt] = (Edge){head[y], y, x, 0, 0};
head[y] = ecnt;
}
int dis[maxn];
bool bfs(int s, int t)
{
Mem(dis, 0); dis[s] = 1;
queue<int> q; q.push(s);
while(!q.empty())
{
int now = q.front(); q.pop();
for(int i = head[now], v; i != -1; i = e[i].nxt)
{
if(!dis[v = e[i].to] && e[i].cap > e[i].flow)
{
dis[v] = dis[now] + 1;
q.push(v);
}
}
}
return dis[t];
}
int cur[maxn];
int dfs(int now, int _t, int res)
{
if(now == _t || res == 0) return res;
int flow = 0, f;
for(int& i = cur[now], v; i != -1; i = e[i].nxt)
{
if(dis[v = e[i].to] == dis[now] + 1 && (f = dfs(v, _t, min(res, e[i].cap - e[i].flow))) > 0)
{
e[i].flow += f; e[i ^ 1].flow -= f;
flow += f; res -= f;
if(res == 0) break;
}
}
return flow;
}
int maxflow(int s, int t)
{
int flow = 0;
while(bfs(s, t))
{
memcpy(cur, head, sizeof(head));
flow += dfs(s, t, INF);
}
return flow;
}
int d[maxn];
void init()
{
Mem(head, -1); ecnt = -1;
s = 0, t = n + 1;
S = t + 1; T = S + 1;
}
int cg(char c)
{
if(c == '+') return s;
if(c == '-') return t;
return c -'0';
}
int main()
{
while(scanf("%d%d", &n, &m))
{
if(!n && !m) break;
init();
for(int i = 1; i <= m; ++i)
{
scanf("%s%s", s1, s2); int w = read();
int x = cg(s1[0]), y = cg(s2[0]);
addEdge(x, y, INF - w);
d[x] += w; d[y] -= w;
}
int tot = 0;
for(int i = 0; i <= t; ++i)
if(d[i] < 0) addEdge(S, i, -d[i]);
else addEdge(i, T, d[i]), tot += d[i];
addEdge(t, s, INF);
if(maxflow(S, T) < tot) puts("impossible");
else
{
int tp = -e[ecnt].flow; e[ecnt ^ 1].flow = e[ecnt ^ 1].cap;
for(int i = head[S]; i != -1; i = e[i].nxt) e[i ^ 1].cap = e[i ^ 1].flow;
for(int i = head[T]; i != -1; i = e[i].nxt) e[i ^ 1].cap = e[i ^ 1].flow;
write(tp - maxflow(t, s)), enter;
}
}
return 0;
}