您的位置:首页 > 其它

UVa10249 - The Grand Dinner(为什么超时)

2013-09-18 19:06 162 查看
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 130;
const int INF = 1000000;

struct Edge
{
int from, to, cap, flow;
};

int m, n;
int s, t;
vector<Edge> vEdge;
vector<int> adjList
;
int d
, p
;

void addEdge(int from, int to, int cap);
void init();
int Edmonds_Karp();
void print();

int main()
{
int total, nMax;
int cap;

#ifndef ONLINE_JUDGE
freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif

while (scanf("%d%d", &m, &n) == 2 && (m || n)) {
s = 0; t = m + n + 1;

init();
total = 0;
nMax = 0;
for (int i = 1; i <= m; i++) {
scanf("%d", &cap);
if (cap > nMax) nMax = cap;
total += cap;

addEdge(s, i, cap);
}

for (int i = m + 1; i <= m + n; i++) {
scanf("%d", &cap);
for (int j = 1; j <= m; j++) {
addEdge(j, i, 1);
}

addEdge(i, t, cap);
}

if (m == 0) {
printf("0\n");
continue;
}

if (nMax > n || n == 0) {
printf("0\n");
continue;
}

int ans = Edmonds_Karp();
if (ans == total) {
printf("1\n");
print();
} else {
printf("0\n");
}
}
return 0;
}

void init()
{
vEdge.clear();

for (int i = 0; i <= t; i++) {
adjList[i].clear();
}
}

void addEdge(int from, int to, int cap)
{
vEdge.push_back((Edge){from, to, cap, 0});
vEdge.push_back((Edge){to, from, 0, 0});

int num = vEdge.size();
adjList[from].push_back(num - 2);
adjList[to].push_back(num - 1);
}

int Edmonds_Karp()
{
int f = 0;

for (;;) {
memset(d, 0x00, sizeof(d));
d[s] = INF;

queue<int> q;
q.push(s);

while (!q.empty()) {
int cur = q.front(); q.pop();
bool flag = false;
for (int i = 0; i < adjList[cur].size(); i++) {
int edgeNo = adjList[cur][i];
Edge &e = vEdge[edgeNo];
if (!d[e.to] && e.cap > e.flow) {
q.push(e.to);
p[e.to] = edgeNo;
d[e.to] = min(d[cur], e.cap - e.flow);

if (e.to == t) {
flag = true;
break;
}
}
}
if (flag) break;
}

if (d[t] == 0) break;

for (int u = t; u != s; u = vEdge[p[u]].from) {
int num = p[u];
vEdge[num].flow += d[t];
vEdge[num ^ 1].flow -= d[t];
}

f += d[t];
}

return f;
}

void print()
{
bool first;

for (int i = 1; i <= m; i++) {
first = true;
for (int j = 0; j < adjList[i].size(); j++) {
int no = adjList[i][j];
Edge &e = vEdge[no];
if (e.flow > 0) {
if (first) first = false;
else printf(" ");

printf("%d", e.to - m);
}
}
printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: