当前位置: 代码迷 >> 综合 >> POJ 1716 差分约束 SPFA
  详细解决方案

POJ 1716 差分约束 SPFA

热度:50   发布时间:2024-01-20 20:53:43.0

和上题一样的解法。代码也一样,一样纠结了很久。一样不知道为什么!!

#include<iostream>
#include<queue>
#define MAXN 20001
#define INF 0x7F7F7F7F
using namespace std;struct Node
{int v,price;Node *next;
}Edge[MAXN<<2],*ptr[MAXN];int N;
int minV,maxV;
int EdgeNum;void addEdge( int u,int v,int w )
{Node *p=&Edge[EdgeNum++];p->v=v;p->price=w;p->next=ptr[u];ptr[u]=p;
}int dist[MAXN];
void spfa( )
{bool used[MAXN];queue<int>myQueue;while( !myQueue.empty() ) myQueue.pop();memset( used,0,sizeof(used) );memset( dist,0xFF,sizeof(dist) );dist[minV]=0;myQueue.push(minV);while( !myQueue.empty() ){int u=myQueue.front();myQueue.pop();Node *p=ptr[u];used[u]=false;while( p ){if( dist[p->v]<dist[u]+p->price ){dist[p->v]=dist[u]+p->price;if( !used[p->v] ){used[p->v]=true;myQueue.push(p->v);}}p=p->next; }}return ;
} 
int main()
{    while( scanf( "%d",&N )!=EOF ){int i,j;int a,b;EdgeNum=0;maxV=0;minV=INF;for( i=0;i<=N;i++ )ptr[i]=NULL;for( i=1;i<=N;i++ ){scanf( "%d %d",&a,&b );if( minV>a )minV=a;if( maxV<b+1 )maxV=b+1;addEdge( a,b+1,2 );}for( i=minV;i<=maxV;i++ ){addEdge( i,i+1,0 );addEdge( i+1,i,-1 );}spfa();printf( "%d\n",dist[maxV] );}return 0;   
}