POJ 3259 Back to the past

#include<stdio.h>

int farms, fields, paths, wormholes;
typedef struct{
	int from;
	int to;
	int seconds;
}edge;
edge edges[5201];
int numOfEdges;

int time[1001];

void addEdge(int from, int to, int seconds){
	edges[numOfEdges].from = from;
	edges[numOfEdges].to = to;
	edges[numOfEdges].seconds = seconds;
	numOfEdges++;
}

int main(){
	setbuf(stdout, NULL);
	//freopen("input.txt", "r", stdin);
	scanf("%d", &farms);
	int farm;
	for (farm = 0; farm < farms; farm++){
		/* input */
		scanf("%d %d %d", &fields, &paths, &wormholes);
		//reset time
		int field;
		for (field = 0; field < fields; field++){
			time[field] = 0;
		}
		//input paths
		numOfEdges = 0;
		int from, to, seconds;
		int path;
		for (path = 0; path < paths; path++){
			scanf("%d %d %d", &from, &to, &seconds);
			addEdge(from, to , seconds);
			addEdge(to, from, seconds);
		}
		//input wromholes
		int wormhole;
		for (wormhole = 0; wormhole < wormholes; wormhole++){
			scanf("%d %d %d", &from, &to, &seconds);
			addEdge(from, to, -seconds);
		}
		/* Bellman-Ford Algorithm */
		//relax
		int toContinue = 0;
		int relax;
		for (relax = 0; relax < fields - 1; relax++){
			int edgeNum;
			for (edgeNum = 0; edgeNum < numOfEdges; edgeNum++){
				if (time[ edges[edgeNum].from ] + edges[edgeNum].seconds < time[ edges[edgeNum].to ]){
					time[ edges[edgeNum].to ] = time[ edges[edgeNum].from ] + edges[edgeNum].seconds;
					toContinue = 1;
				}
			}
			if (!toContinue){
				break;
			}
		}
		//canAchieve?
		int canAchieve = 0;
		int edgeNum;
		for (edgeNum = 0; edgeNum < numOfEdges; edgeNum++){
			if (time[ edges[edgeNum].from ] + edges[edgeNum].seconds < time[ edges[edgeNum].to ]){
				canAchieve = 1;
				break;
			}
		}
		/* ouput */
		if (canAchieve){
			printf("YES\n");
		} else {
			printf("NO\n");
		}	
	}//end of for (farm = 0; farm < farms; farm++)
	return 0;
}

你可能感兴趣的:(TO,poj,back,the,past,3259)