ford变种算法,求是否存在正权回路
点击(此处)折叠或打开
- #include <iostream>
- #include <map>
- #include <cstring>
-
- using namespace std;
-
- #define MAX_V (30+1)
- #define inf (2000000000)
- double E[MAX_V][MAX_V];
- double D[MAX_V];
- map<string,int> M;
-
-
- int n,m;
- int index_v=1;
-
- void solve(int index_v)
- {
- int found = 0;
-
- for(int k=1;k<=n;k++)
- {
- if(E[1][k] != 0)
- {
- D[k] = E[1][k];
- }
- }
- for(int i=1;i<=n-1;i++)
- {
- int flag = 0;
-
- //foreach u,v
- for(int j=1;j<=n;j++)
- {
- for(int k=1;k<=n;k++)
- {
- if(E[j][k] != 0)
- {
- //each edge j->k
- double kw=D[j] * E[j][k];
- if(kw > D[k])
- {
- D[k]= kw;
- flag=1;
- }
- }
- }
- }
-
- if(!flag)
- break;
- }
-
- //foreach u,v
- for(int j=1;j<=n;j++)
- {
- for(int k=1;k<=n;k++)
- {
- if(E[j][k] != 0)
- {
- //each edge j->k
- double kw=D[j] * E[j][k];
- if(kw > D[k])
- {
- D[k]= kw;
- cout<<"Case "<<index_v<<": Yes"<<endl;
- return;
- }
- }
- }
- }
-
- cout<<"Case "<<index_v<<": No"<<endl;
- }
- int main()
- {
- while(cin>>n)
- {
-
- if(n == 0)
- break;
-
- memset(E,0,sizeof(E));
- for(int i=1;i<=n;i++)
- {
- string name;
- cin>>name;
-
- M[name]=i;
- }
-
- cin>>m;
-
- for(int i=1;i<=m;i++)
- {
- string namei,namej;
- double rij;
- int vi,vj;
-
- cin>>namei>>rij>>namej;
-
- vi=M[namei];
- vj=M[namej];
- E[vi][vj]=rij;
- }
-
- solve(index_v);
- index_v++;
- }
- }
相关热门文章
给主人留下些什么吧!~~
评论热议