做了两道差分约束的题目。但是都是用的bellman-ford来写的。其中POJ1201开始的时候TLE 了,就是在最后一个更新的时候由min到max的更新d[ ].这样的话会重复操作。后来将其由max到min就200+飘过。POJ2983是最开始的时候存边点的时候有问题。所以WA。后来改了之后就AC了。用的是bellman-ford所以几乎是压着线过去的。
上代码(POJ2983):
#include<cstdio>
using namespace std;
struct node{
int v,u,weight;
};
node edge[300010];
int d[1010];
int edgenum,nodenum,maxint=100000000;
int bellman_ford(){
int i,j;
for(i=0;i<=nodenum;i++){
d[i]=maxint;
}
d[1]=0;
for(i=1;i<=nodenum;i++){
bool flag=1;
for(j=0;j<=edgenum-1;j++){
if(d[edge[j].v]>d[edge[j].u]+edge[j].weight)
d[edge[j].v]=d[edge[j].u]+edge[j].weight;
flag=0;
}
if(flag==1)
break;
}
for(j=0;j<=edgenum-1;j++){
if(d[edge[j].v]>d[edge[j].u]+edge[j].weight)
return 0;
}
return 1;
}
main(){
int m,n,i,j,k,ev,eu,w;
char ch;
while(scanf("%d%d",&n,&m)!=-1){
getchar();
k=0;
for(i=0;i<=m-1;i++){
scanf("%c",&ch);
if(ch=='P'){
scanf("%d%d%d",&eu,&ev,&w);
edge[k].u=ev;
edge[k].v=eu;
edge[k++].weight=w;
edge[k].u=eu;
edge[k].v=ev;
edge[k++].weight=-w;
}
if(ch=='V'){
scanf("%d%d",&eu,&ev);
edge[k].u=eu;
edge[k].v=ev;
edge[k++].weight=-1;
}
getchar();
}
edgenum=k;
nodenum=n;
if(bellman_ford())
printf("Reliable\n");
else{
printf("Unreliable\n");
}
}
}
(POJ1201)
#include<cstdio>
#include<cmath>
using namespace std;
struct node{
int u;
int v;
int weight;
};
node edge[50100];
int nodemax=0,edgenum,nodemin=1000000;
int maxint=100000000;
int d[50100];
int bellman_ford(){
int i,j;
for(i=nodemin;i<=nodemax;i++){
d[i]=-1;
}
d[nodemin]=0;
for(i=nodemin;i<=nodemax;i++){
bool flag=0;
for(j=0;j<=edgenum-1;j++){
if(d[edge[j].u]!=-1 && d[edge[j].u]+edge[j].weight>d[edge[j].v]){
d[edge[j].v]=d[edge[j].u]+edge[j].weight;
flag=1;
}
}
for(j=nodemin;j<=nodemax-1;j++){
if(d[j]!=-1 && d[j]>d[j+1]){
d[j+1]=d[j];
flag=1;
}
}
for(j=nodemax;j>=nodemin-1;j--){
if(d[j]!=-1 && d[j]-1>d[j-1]){
d[j-1]=d[j]-1;
flag=1;
}
}
if(flag==0)break;
}
//printf("%d %d\n",d[nodemax],d[nodemin]);
return d[nodemax]-d[nodemin];
}
int main(){
int n,i;
int ev,eu,w;
scanf("%d",&n);
for(i=0;i<=n-1;i++){
scanf("%d%d%d",&eu,&ev,&w);
edge[i].u=eu;
edge[i].v=ev+1;
edge[i].weight=w;
if(ev+1>nodemax)
nodemax=ev+1;
if(eu<nodemin){
nodemin=eu;
}
}
edgenum=n;
printf("%d\n",bellman_ford());
return 0;
}