面壁:
细节之处,尽显实力;
spfa + vector
#include <iostream> #include <cstdio> #include <vector> #include <stack> using namespace std; #define inf 99999999 #define V 520 #define NE 6000 int n,m,w; struct node { int v; int val; }E; vector<node> Node[V+2]; int spfa(int k) { int d[V], cnt[V], vis[V]; for(int j = 1;j <= n;j ++) d[j] = inf,cnt[j] = 0,vis[j] = 0; d[k] = 0; vis[k] = 1;cnt[k] = 1; stack<int> p;p.push(k); while(!p.empty()) { int u = p.top();
p.pop();vis[u] = 0; int len = Node[u].size(); for(int j = 0;j < len;j ++) { int v = Node[u][j].v; int c=Node[u][j].val; if(d[v] - c > d[u]) { d[v] = c + d[u]; if(!vis[v]) { vis[v] = 1; cnt[v] ++; if(cnt[v] >= n) return 1; p.push(v); } } } } return 0; } int main() { int cs; scanf("%d",&cs); while(cs--) { scanf("%d%d%d",&n,&m,&w); for(int j = 1;j <= n;j ++) Node[j].clear(); while(m--) { int a,b,c; scanf("%d%d%d",&a,&b,&c); E.v = b; E.val = c; Node[a].push_back(E); E.v = a; E.val = c; Node[b].push_back(E); } while(w--) { int a,b,c; scanf("%d%d%d",&a,&b,&c); E.v = b;E.val = -c; Node[a].push_back(E); } if(!spfa(1)) puts("NO"); else puts("YES"); } return 0; }
spfa + 数组模拟(很有意思的写法)
#include<stdio.h> #include<string.h> #define V 510 #define E 6000 #define inf 999999999 int pnt[E],nxt[E],cost[E]; int head[V],e; int spfa(int n,int m,int s) { int dist[V],vis[V],cnt[V]; for(int i=1;i<=n;i++) dist[i]=inf,vis[i]=0,cnt[i]=0; dist[s]=0;vis[s]=1;cnt[s]++; int que[E],top=1; que[0]=s; while(top) { int u=que[--top];vis[u]=0; for(int i=head[u];i!=-1;i=nxt[i]) { int v=pnt[i]; if(dist[v] > dist[u]+cost[i]) { dist[v]=dist[u]+cost[i]; if(!vis[v]) { vis[v]=1;cnt[v]++; if( cnt[v] >= n) return 1; que[top++]=v; } } } } return 0; } void add(int u,int v,int c) { pnt[e]=v; cost[e]=c; nxt[e]=head[u];head[u]=e++; } int main() { int cs;scanf("%d",&cs); while(cs--) { int n,m,w;e=0; memset(head,-1,sizeof(head)); scanf("%d%d%d",&n,&m,&w); while(m--) { int s,e,c;scanf("%d%d%d",&s,&e,&c); add(s,e,c); add(e,s,c); } while(w--) { int s,e,c;scanf("%d%d%d",&s,&e,&c); add(s,e,-c); } if(spfa(n,e,1))puts("YES"); else puts("NO"); } return 0; }
bellamn 复杂度(VE)
虽然复杂度高点,还是有点情有独钟->__-->
#include<stdio.h> #define V 510 #define E 6000 #define inf 999999999 struct node { int s,e,c; }map[E]; int bellman(int n,int m,int s) { int dist[V]; for(int i=1;i<=n;i++) dist[i]=inf;dist[s]=0; for(int i=1;i<n;i++) { int flag=0; for(int j=0;j<m;j++) { int u=map[j].s; int v=map[j].e; int c=map[j].c; if(dist[v]>dist[u]+c) dist[v]=dist[u]+c; flag=1; } if(!flag) break; } for(int j=0;j<m;j++) { int u=map[j].s; int v=map[j].e; int c=map[j].c; if(dist[v]>dist[u]+c) return 1; } return 0; } int main() { int cs;scanf("%d",&cs); while(cs--) { int n,m,w,top=0; scanf("%d%d%d",&n,&m,&w); while(m--) { int s,e,c;scanf("%d%d%d",&s,&e,&c); map[top].s=s,map[top].e=e,map[top++].c=c; map[top].s=e,map[top].e=s,map[top++].c=c; } while(w--) { int s,e,c;scanf("%d%d%d",&s,&e,&c); map[top].s=s,map[top].e=e,map[top++].c=-c; } if(bellman(n,top,1))puts("YES"); else puts("NO"); } return 0; }