URAL 1162 Currency Exchange (Bellman-Ford贝尔曼-福特算法)

#include <stdio.h>

int numOfCurrencies, numOfExchPoints, NickCurrencyNum;
double NickCurrencyAmount;
typedef struct Exchange{
	int from;
	int to;
	double rate;
	double commisssions;
}Exchange;
Exchange ExchangeArray[100000];
int numOfExchanges;
//wealth[currency]表示当把财富换成类型为currency的现金时的数量
double wealth[200];

int exchangeToIncrease(){
	wealth[NickCurrencyNum] = NickCurrencyAmount;
	int relax;
	for (relax = 1; relax < numOfCurrencies; relax++){
		int needContinue = 0;
		int ExchangeIndex;
		for (ExchangeIndex = 1; ExchangeIndex <= numOfExchanges; ExchangeIndex++){
			Exchange currentExchange = ExchangeArray[ExchangeIndex];
			//Bellman-Ford算法还能这样用!!!
			double wealthExchanged = (wealth[currentExchange.from] - currentExchange.commisssions) * currentExchange.rate;
			if ( wealthExchanged > wealth[currentExchange.to]){
				needContinue = 1;
				wealth[currentExchange.to] = wealthExchanged;
			}
		}
		if (!needContinue)
			break;
	}

	int ExchangeIndex;
	for (ExchangeIndex = 1; ExchangeIndex <= numOfExchanges; ExchangeIndex++){
		Exchange currentExchange = ExchangeArray[ExchangeIndex];
			if ( (wealth[currentExchange.from] - currentExchange.commisssions) * currentExchange.rate > wealth[currentExchange.to] )
				return 1;
	}
	return 0;
}

void addExchange(int from, int to, double rate, double comissions){
	numOfExchanges++;
	int ExchangeNum = numOfExchanges;
	ExchangeArray[ExchangeNum].from = from;
	ExchangeArray[ExchangeNum].to = to;
	ExchangeArray[ExchangeNum].rate = rate;
	ExchangeArray[ExchangeNum].commisssions = comissions;
}

int main(){
	
	scanf("%d%d%d%lf", &numOfCurrencies, &numOfExchPoints, &NickCurrencyNum, &NickCurrencyAmount);
	int exchangePoint;
	for (exchangePoint = 1; exchangePoint <= numOfExchPoints; exchangePoint++){
		int a, b;
		double rab, cab, rba, cba;
		scanf("%d%d%lf%lf%lf%lf", &a, &b, &rab, &cab, &rba, &cba);
		addExchange(a, b, rab, cab);
		addExchange(b, a, rba, cba);
	}

	printf("%s\n", exchangeToIncrease() == 1 ? "YES" : "NO");

	return 0;
}

你可能感兴趣的:(Exchange,currency,Bellman-Ford,ural,1162,贝尔曼-福特)