又是一道Bellman-ford练手,我感觉poj的服务器不是很稳定,一次wa,做了点无伤大雅的改动说我超时,过了一会儿又提交的时候说是CE,然后我加了两个初始化之后就ac了。
还是贴代码:
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
struct edge{
string cu1;
string cu2;
double rate;
edge(string s1,string s2,double d){
cu1=s1; cu2=s2; rate=d;
}
};
vector<edge> collection_edges;
map<string,double> money;
int num_edges=0;
int num_currencies=0;
bool relax(int i){
bool flag=true;
double m1=money[collection_edges[i].cu1];
double m2=money[collection_edges[i].cu2];
if(m2<m1*collection_edges[i].rate){
money[collection_edges[i].cu2]=m1*collection_edges[i].rate;
flag=false;
}
return flag;
}
bool bellman_ford(){
for(int m=0;m<num_currencies-1;m++){
for(int i=0;i<num_edges;i++){
relax(i);
}
}
for(int i=0;i<num_edges;i++){
if(money[collection_edges[i].cu2]<money[collection_edges[i].cu1]*collection_edges[i].rate)
return true;
}
return false;
}
int main(int argc, const char * argv[]) {
int no_case=1;
while(cin>>num_currencies){
if(num_currencies==0)
break;
for(int i=0;i<num_currencies;i++){
string name;
cin>>name;
money.insert(pair<string,double>(name,0.0));
}
cin>>num_edges;
for(int i=0;i<num_edges;i++){
string name1,name2;
double r=0;
cin>>name1>>r>>name2;
edge e(name1,name2,r);
collection_edges.push_back(e);
}
money[collection_edges[0].cu1]=1.0;
if(bellman_ford()) cout<<"Case "<<no_case<<": Yes"<<endl;
else cout<<"Case "<<no_case<<": No"<<endl;
collection_edges.clear();
money.clear();
no_case++;
}
return 0;
}