本题是最短路判断图中是否存在正环的题,可用bellman_ford和spfa来做,记得再第一种做法的结构体的定义中要开大于>100的数,不然会runtime error,关于spfa,利用vector来实现保存,并且用stack来存会比queue快一些,详情见代码
bellman_ford:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=200+20;
struct node{
int u,v;
double r,c;
}p[maxn];
int n,m,s,cnt;
double v;
double dis[maxn];
bool bellman_ford(int x)
{
sizeof(dis,0,sizeof(dis));
dis[x]=v;
for(int i=1;i<n;i++)
{
bool flag=false;
for(int j=0;j<cnt;j++)
{
//cout<<"hrer"<<endl;
int a1=p[j].u,b1=p[j].v;
double rate=p[j].r,commiss=p[j].c;
// cout<<rate<<" "<<commiss<<endl;
if(dis[b1]<(dis[a1]-commiss)*rate)
{
dis[b1]=(dis[a1]-commiss)*rate;
//cout<<dis[b1]<<endl;
flag=true;
}
}
if(!flag) break;
}
for(int i=0;i<cnt;i++)
if(dis[p[i].v]<(dis[p[i].u]-p[i].c)*p[i].r)
return true;
return false;
}
int main()
{
int a,b;
double c1,d1,c2,d2;
//freopen("E.txt","r",stdin);
cnt=0;
scanf("%d %d %d %lf",&n,&m,&s,&v);
while(m--)
{
scanf("%d %d %lf %lf %lf %lf",&a,&b,&c1,&d1,&c2,&d2);
//cout<<c1<<d1<<endl;
p[cnt].u=a,p[cnt].v=b,p[cnt].r=c1,p[cnt++].c=d1;
p[cnt].u=b,p[cnt].v=a,p[cnt].r=c2,p[cnt++].c=d2;
}
if(bellman_ford(s))
printf("YES\n");
else
printf("NO\n");
return 0;
}
spfa:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
const int maxn=200+20;
struct node{
int u,v;
double r,c;
};
node eg;
int n,m,s;
double v;
double dis[maxn];
int vis[maxn],count[maxn];
vector<node> p[maxn];
bool spfa(int x)
{
sizeof(count,0,sizeof(count));
sizeof(vis,0,sizeof(vis));
sizeof(dis,0,sizeof(dis));
dis[x]=v;
stack<int> st;
st.push(x);vis[x]=1;
while(!st.empty())
{
int pip=st.top();st.pop();
vis[pip]=0;
for(int i=0;i<p[pip].size();i++)
{
int b1=p[pip][i].v;
double cost=p[pip][i].c;
double rate=p[pip][i].r;
if(dis[b1]<(dis[pip]-cost)*rate)
{
dis[b1]=(dis[pip]-cost)*rate;
if(vis[b1]) continue;
vis[b1]=1;
count[b1]++;
if(count[b1]>n) return true;
st.push(b1);
}
}
}
return false;
}
int main()
{
int a,b;
double c1,d1,c2,d2;
//freopen("E.txt","r",stdin);
scanf("%d %d %d %lf",&n,&m,&s,&v);
while(m--)
{
scanf("%d %d %lf %lf %lf %lf",&a,&b,&c1,&d1,&c2,&d2);
eg.u=a,eg.v=b,eg.r=c1,eg.c=d1;
p[a].push_back(eg);
eg.u=b,eg.v=a,eg.r=c2,eg.c=d2;
p[b].push_back(eg);
}
if(spfa(s))
printf("YES\n");
else
printf("NO\n");
return 0;
}