POJ 2240(水题 条件改变的 floyd 算法)

来源:互联网 发布:多人直播源码 编辑:程序博客网 时间:2024/06/03 23:48

POJ2240

题意:有n种类型的货币求是否存在经过兑换能增值。

思路:改变条件即可。


#include<iostream>#include<cstdio>#include<cstring>using namespace std;int n;double dist[100][100];char str[100][100];int find_it(char a[]){    for(int i = 1;i <= n; i++){        if(strcmp(a,str[i]) == 0)            return i;    }}int main(){    int ncase = 1;    while(ncase)    {        cin>>n;        if(!n)            break;        for(int i = 1;i <= n; i++)            cin>>str[i];        memset(dist,0,sizeof(dist));    //初始化        for(int i = 0;i <= n; i++)      //自己兑换率为1            dist[i][i] = 1;        int n1;        cin>>n1;        for(int i = 1;i <= n1; i++){            char a[100],b[100];            double rate;            cin>>a>>rate>>b;            dist[find_it(a)][find_it(b)] = rate;        }        for(int k = 1;k <= n; k++)            for(int i = 1;i <= n; i++)                for(int j = 1;j <= n; j++)                    if(dist[i][j] < dist[i][k]*dist[k][j])      //条件改变,易理解                        dist[i][j] = dist[i][k]*dist[k][j];        int flag = 0;        for(int i = 1;i <= n; i++)        {            if(dist[i][i] > 1){                printf("Case %d: Yes\n",ncase++);                flag = 1;                break;            }        }        if(!flag)            printf("Case %d: No\n",ncase++);    }    return 0;}

也可以用map制造一个string与int对应的容器

#include<iostream>#include<cstdio>#include<cstring>#include<map>using namespace std;int n;double dist[100][100];char str[100][100];map<string,int>q;/*int find_it(char a[]){    for(int i = 1;i <= n; i++){        if(strcmp(a,str[i]) == 0)            return i;    }}*/int main(){    int ncase = 1;    while(ncase)    {        cin>>n;        if(!n)            break;        for(int i = 1;i <= n; i++){            cin>>str[i];            q[str[i]] = i;        }        memset(dist,0,sizeof(dist));    //初始化        for(int i = 0;i <= n; i++)      //自己兑换率为1            dist[i][i] = 1;        int n1;        cin>>n1;        for(int i = 1;i <= n1; i++){            char a[100],b[100];            double rate;            cin>>a>>rate>>b;            dist[q[a]][q[b]] = rate;        }        for(int k = 1;k <= n; k++)            for(int i = 1;i <= n; i++)                for(int j = 1;j <= n; j++)                    if(dist[i][j] < dist[i][k]*dist[k][j])      //条件改变,易理解                        dist[i][j] = dist[i][k]*dist[k][j];        int flag = 0;        for(int i = 1;i <= n; i++)        {            if(dist[i][i] > 1){                printf("Case %d: Yes\n",ncase++);                flag = 1;                break;            }        }        if(!flag)            printf("Case %d: No\n",ncase++);    }    return 0;}


0 0
原创粉丝点击