Pagini recente » Cod sursa (job #8018) | Cod sursa (job #2907446) | Cod sursa (job #2906651) | Cod sursa (job #2710517) | Cod sursa (job #55140)
Cod sursa(job #55140)
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
enum { maxn = 1024, maxe = 10001, inf = 0x3F3F3F3F };
int n;
int d[maxn][maxn];
int e;
int ee[maxe][2];
int theflow;
int ans[maxe], w;
bool source[maxn], sink[maxn]; //reachability in residual graph
int who[maxe * 2], prev[maxe * 2]; //size??
int last[maxn], unused;
int f[maxn];
int parent[maxn];
int q[maxn], qs, qe;
inline void add(int from, int to)
{
who[unused] = to;
prev[unused] = last[from];
last[from] = unused;
unused++;
}
void bfs()
{
int i, the, first;
qs = 0;
qe = 1;
q[0] = 0; //source
f[0] = inf;
memset(parent, 0xFF, sizeof(parent)); //-1
parent[0] = -2; //calc'ed
while(qs != qe)
{
first = q[qs]; //I hope G++ knows what it's doing.
qs++;
for(i = last[first]; i != -1; i = prev[i])
{
the = who[i];
if(d[first][the] && parent[the] == -1) //not calc'ed
{
parent[the] = first;
f[the] = std::min(f[first], d[first][the]);
if(the == n - 1) //sink
return;
q[qe++] = the;
}
}
}
//can't reach sink.
}
void maxflow()
{
int i, add;
while(true) //increase flow
{
bfs();
if(parent[n - 1] == -1) //didn't reach sink
return;
add = f[n - 1];
assert(add != 0);
theflow += add;
for(i = n - 1; i; i = parent[i])
{
assert(i > 0);
assert(parent[i] >= 0);
d[i][ parent[i] ] += add;
d[ parent[i] ][i] -= add;
}
}
//unreachable
}
void df(bool *tab, int node)
{
assert(!tab[node]);
tab[node] = true;
int i, the;
for(i = last[node]; i != -1; i = prev[i])
{
the = who[i];
if(!tab[the] && d[node][the] && d[the][node]) //both ways, because we remove saturated edges
df(tab, the);
}
}
int main()
{
int i, tmp, a, b;
FILE *f = fopen("critice.in", "r");
if(!f) return 1;
fscanf(f, "%d%d", &n, &e);
memset(last, 0xFF, sizeof(last)); //-1
for(i = 0; i < e; i++)
{
fscanf(f, "%d%d%d", &a, &b, &tmp);
a--; b--;
ee[i][0] = a;
ee[i][1] = b;
d[a][b] = tmp;
d[b][a] = tmp;
add(a, b);
add(b, a);
}
fclose(f);
f = fopen("critice.out", "w");
if(!f) return 1;
maxflow();
df(source, 0);
df(sink, n - 1);
for(i = 0; i < e; i++)
{
a = ee[i][0];
b = ee[i][1];
if( (d[a][b] == 0 && source[a] && sink[b]) ||
(d[b][a] == 0 && source[b] && sink[a]) )
ans[w++] = i;
}
fprintf(f, "%d\n", w);
for(i = 0; i < w; i++)
fprintf(f, "%d\n", ans[i] + 1);
fclose(f);
return 0;
}