用bellman-ford判环,注意大小于号
如果有环路的话,就可以连续进行,特别适用于增值钞票,用于汇率交换,当然要考虑到不是连通图的情况。
#include <iostream>
#include <map>
#include <string.h>
#include <string>
using namespace std;
const int size = 31;
int n;
map<string, int> str2ix;
double road[size][size];
double dis[size];
bool bf(){
memset(dis, 0, sizeof(dis));
dis[0] = 1;
bool flag = false;
for (int i = 0; i < n - 1; ++i) {
flag = false;
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k) {
// relax the edge
if (road[j][k]&&dis[k]<dis[j]*road[j][k]){
dis[k] = dis[j]*road[j][k];
flag = true;
}
}
}
if (!flag) return false;
}
// check the circle;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (road[i][j]&&dis[j]<dis[i]*road[i][j])
return true;
}
}
return false;
}
int main(){
string ss;
int ix = 0;
while (scanf("%d", &n)&&n){
memset(road, 0, sizeof(road));
for (int i = 0; i < n; ++i) {
cin>>ss;
str2ix[ss] = i;
}
int m;
cin>>m;
for (int i = 0; i < m; ++i) {
string s1; double r; string s2;
cin>>s1>>r>>s2;
road[str2ix[s1]][str2ix[s2]] = r;
}
/**
* bellman-ford algorithm
*/
printf("Case %d: ",++ix);
puts(bf()?"Yes":"No");
}
}
#include <iostream>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
using namespace std;
map<string, int> str2ix;
struct Edge {
int a, b;
double c;
Edge(int a, int b, double c) : a(a), b(b), c(c) {}
};
vector<Edge> edgelist;
int n;
int m;
const int MAXSIZE = 105;
double dis[MAXSIZE];
bool bf(){
memset(dis, 0, sizeof(dis)); //IEEE754的0也是全0表示
dis[0] = 1;
bool flag;
for (int i = 0; i < n - 1; ++i) {
flag = false;
for (int j = 0; j < edgelist.size(); ++j) {
Edge edge = edgelist[j];
if (dis[edge.b]<dis[edge.a]*edge.c){
dis[edge.b] = dis[edge.a]*edge.c;
flag = true;
}
}
if (!flag)
return false;
}
for (int j = 0; j < edgelist.size(); ++j) {
Edge edge = edgelist[j];
if (dis[edge.b] < dis[edge.a] * edge.c) {
return true;
}
}
return false;
}
int main() {
int cnt = 1;
// freopen("../in.txt", "r", stdin);
while (true) {
cin >> n;
if (n == 0) break;
string temp;
for (int i = 0; i < n; ++i) {
cin >> temp;
str2ix[temp] = i;
}
cin>>m;
string a, b;
double c;
for (int i = 0; i < m; ++i) {
cin>>a>>c>>b;
int temp1, temp2;
temp1 = str2ix[a], temp2 = str2ix[b];
edgelist.push_back(Edge(temp1, temp2, c));
}
printf("Case %d: ",cnt);
cnt++;
bool ok = false;
for (int i = 0; i < n; ++i) {
if (bf()){
puts("Yes");
ok = true;
break;
}
}
if (!ok) puts("No");
edgelist.clear();
str2ix.clear();
}
}