题意:详见bellman-ford解法那
思路: 用spfa 做,原应考虑以每个点为源点判断有无负环,可能是后台数据弱的原因,只要判断第一个点就行了
#include <stdio.h>
#include <string.h>
#define inf 0x3f3f3f3f
#define M 505
#define MAX 6000
int next[MAX],head[M],ep;
struct edge
{
int v,cost;
int next;
}e[MAX];
//边的存储形式
void addedge(int cu,int cv,int w)
//生成边函数
{
ep ++;
e[ep].v = cv;
e[ep].cost = w;
e[ep].next = head[cu];
// next[ep] = head[cu];
head[cu] = ep;
}
int spfa (int n)
{
int inq[M],dis[M],cnt[M],queue[M];
for (int i = 1;i <= n;i ++)
{
dis[i] = inf;
inq[i] = 0;
cnt[i] = 0;
}
dis[1] = 0;
inq[1] = 1;
cnt[1] = 1;
int front = -1,rear = 0;
queue[rear++] = 1;
while (front != rear)
{
front = (front+1)%(n+1);
//循环队列 %(n+1)是为了避免rear == front
int u = queue[front];
inq[u] = 0;
for (int i = head[u];i != -1;i = e[i].next)
//访问所有与它相连的边
{
if (dis[e[i].v] > dis[u] + e[i].cost)
//松驰
{
dis[e[i].v] = dis[u] + e[i].cost;
if (!inq[e[i].v])
{
inq[e[i].v] = 1;
if (++cnt[e[i].v] >= n)
return 0;
queue[rear] = e[i].v;
rear = (rear+1)%(n+1);
}
}
}
}
return 1;
}
int main ()
{
int f,n,m,h,w,v1,v2;
scanf ("%d",&f);
while (f--)
{
ep = 0;
memset (head,-1,sizeof(head));
scanf ("%d%d%d",&n,&m,&h);
while (m --)
{
scanf ("%d%d%d",&v1,&v2,&w);
addedge(v1,v2,w);
addedge(v2,v1,w);
}
while (h--)
{
scanf ("%d%d%d",&v1,&v2,&w);
addedge(v1,v2,-1*w);
}
int ans = spfa (n);
if (!ans)
printf ("YES\n");
else
printf ("NO\n");
}
return 0;
}
思路:
#include <stdio.h>
#include <string.h>
#define inf 0x3f3f3f3f
#define M 505
#define MAX 6000
int next[MAX],head[M],ep;
struct edge
{
}e[MAX];
void addedge(int cu,int cv,int w)
{
}
int spfa (int n)
{
}
int main ()
{
}