PTA代码段错误...百思不知其解
这是PTA上的一道universal travel sites的问题。本质上就是求最大流量。
输入:(EAR MAR AAA BBB这些都表示地名,除第一行的数字表示下面的行数以外,其余数字都表示两个地点之间的最大流量)
EAR MAR 11
EAR AAA 300
EAR BBB 400
AAA BBB 100
AAA CCC 400
AAA MAR 300
BBB DDD 400
AAA DDD 400
DDD AAA 100
CCC MAR 400
DDD CCC 200
DDD MAR 300
输出700(即EAR, MAR之间的最大流量)。
我的代码是这样的,...但是有两个测试点是段错误..百思不得其解,还望大神指点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 20
#define Infinite 10000
int graph[max][max] = {0};
char* nameID[max] = {NULL};
int size = 0;
int get(char* s);
int fluenceBFS(char * s, char *d);
int maxBFS(char* source, char* destination);
int flu[max];
int main()
{
char planet_s[4];
char planet_d[4];
char source[4], destination[4];
int capacity;
int N,i;
int x, y, ans;
scanf("%s",planet_s);
get(planet_s);
scanf("%s",planet_d);
get(planet_d);
scanf("%d", &N);
for(i = 0; i < N; i++){
scanf("%s", source);
scanf("%s", destination);
scanf("%d", &capacity);
x = get(source);
y = get(destination);
graph[x][y] = capacity;
}
ans = maxBFS(planet_s, planet_d);
printf("%d", ans);
}
int get(char* s)
{
int i;
for(i = 0; i < size; i++){
if(strcmp(s, nameID[i]) == 0)
return i;
}
nameID[size] = malloc(sizeof(char) * 4);
if(nameID[size] == NULL) exit(-1);
strcpy(nameID[size], s);
size++;
return (size - 1);
}
int fluenceBFS(char * s, char *d)
{
int queue[max];
int front = 0, rear = 0;
int i,t;
int f[max] = {0};
f[get(s)] = Infinite;
for(i = 0; i < max; i++)
flu[i] = -1;
queue[rear++] = get(s);
while(front != rear)
{
t = queue[front++];
if(t == get(d)) break;
for(i = 0; i < max; i++){
if(graph[t][i] != 0 && flu[i] == -1){
flu[i] = t;
if(f[t] >= graph[t][i]) f[i] = graph[t][i];
else f[i] = f[t];
queue[rear++] = i;
}
}
}
return(f[get(d)]);
}
int maxBFS(char* source, char* destination)
{
int maxf = 0;
int fluence;
int i,v;
while(1)
{
fluence = fluenceBFS(source, destination);
if(fluence == 0) break;
maxf += fluence;
v = get(destination);
while(v != get(source) && v != -1){
i = flu[v];
graph[i][v] -= fluence;
graph[v][i] += fluence;
v = i;
}
}
return maxf;
}