poj2240 - Arbitrage

                                   想看更多的解题报告: http://blog.csdn.net/wangjian8006/article/details/7870410
                                     转载请注明出处:
http://blog.csdn.net/wangjian8006

题目大意:可以简单描述为知道从i到j的汇率,问能不能赚钱

解题思路:问能不能赚钱,就是当i到i初始是t时,从i到i的最长路径能不能大于t,如果有这样的情况就是能赚钱

 

/*
floyd
Memory 196K
Time   47MS
*/
#include <iostream>
#include <string.h>
using namespace std;
#define MAXC 100
#define MAXV 50

double map[MAXV][MAXV];
int n,m;

void Input(){
	char s[MAXV][MAXC],a[MAXC],b[MAXC];
	int i,k,j;
	double c;
	for(i=0;i<=n;i++)
		for(j=0;j<=n;j++)
			if(i==j)
				map[i][j]=1;
			else
				map[i][i]=0;
	for(i=1;i<=n;i++) scanf("%s",s[i]);
	scanf("%d\n",&m);
	for(i=1;i<=m;i++){
		scanf("%s %lf %s",a,&c,b);
		for(j=1;j<=n;j++)
			if(!strcmp(s[j],a)) break;
		for(k=1;k<=n;k++)
			if(!strcmp(s[k],b)) break;
		map[j][k]=c;
	}
}

void floyd(){
	int i,j,k;
	for(k=1;k<=n;k++)
		for(i=1;i<=n;i++)
			for(j=1;j<=n;j++)
				if(map[i][k]*map[k][j]>map[i][j])
					map[i][j]=map[i][k]*map[k][j];
}

int main(){
	int cas=1,i;
	while(scanf("%d\n",&n) && n){
		Input();
		floyd();
		printf("Case %d: ",cas++);
		for(i=1;i<=n;i++)
			if(map[i][i]>1) break;
		if(i>n) printf("No\n");
		else printf("Yes\n");
	}
	return 0;
}


===========================================================================================

 

/*
bellman-ford
Memory 196K
Time   47MS 
*/
#include <iostream>
#include <string.h>
using namespace std;
#define MAXC 100
#define MAXV 50
#define MAXM 10000

typedef struct{
	int a,b;
	double rate;
}Edge;

Edge edge[MAXM];
int n,m;

void Input(){
	char s[MAXV][MAXC],a[MAXC],b[MAXC];
	int i,k,j;
	for(i=1;i<=n;i++) scanf("%s",s[i]);
	scanf("%d\n",&m);
	for(i=1;i<=m;i++){
		scanf("%s %lf %s",a,&edge[i].rate,b);
		for(j=1;j<=n;j++)
			if(!strcmp(s[j],a)) break;
		for(k=1;k<=n;k++)
			if(!strcmp(s[k],b)) break;
		edge[i].a=j;
		edge[i].b=k;
	}
}

int bellman_ford(){
	int i,j;
	double d[MAXV];
	for(i=1;i<=n;i++) d[i]=0;
	d[1]=1;
	for(i=1;i<=n;i++){
		for(j=1;j<=m;j++)
			if(d[edge[j].a]*edge[j].rate>d[edge[j].b])
				d[edge[j].b]=d[edge[j].a]*edge[j].rate;
	}
	for(j=1;j<=m;j++)
		if(d[edge[j].a]*edge[j].rate>d[edge[j].b])
			return 1;
	return 0;
}

int main(){
	int cas=1,i;
	while(scanf("%d\n",&n) && n){
		Input();
		printf("Case %d: ",cas++);
		if(!bellman_ford()) printf("No\n");
		else printf("Yes\n");
	}
	return 0;
}


 

你可能感兴趣的:(c,struct,input)