World Exhibition hdu 3592 差分约束
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <deque>
using namespace std;
const int inf = 0x7f7f7f7f;
struct node
{
int x, v;
}Nd;
int N1,M1,P1,f1;
vector<node>T[11010];
deque<int>q;
bool flag[11010] = {false};
int dis[11020];
int hash[11020];
void debug( )
{
#ifdef P
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
}
int spfa( )
{
int t;
vector<node>::iterator iter;
q.push_back(1);
dis[1] = 0;
flag[1] = 1;
while ( !q.empty( ) )
{
t = q.front( );
flag[t] = 0;
q.pop_front( );
for ( iter = T[t].begin( ); iter != T[t].end( ); iter++) {
if ( dis[iter->x] > dis[t] + iter->v ) {
dis[iter->x] = dis[t] + iter->v;
if ( !flag[iter->x] )
{
flag[iter->x] = 1;
q.push_back(iter->x);
}
if ( ++hash[iter->x] > P1)
{
return -1;
}
}
}
}
if (dis[P1] == inf)
return -2;
return dis[P1];
}
void init( )
{
int i;
q.clear();
for (i = 0; i <= 1000; i++)
T[i].clear(), flag[i] = 0;
memset(dis, 0, sizeof(dis));
memset(hash, 0, sizeof(hash));
for ( i = 1; i <= 1000; i++) {
dis[i] = inf;
}
}
void print( int x)
{
int i;
for (i = 0; i <= x; i++)
printf("%d ",dis[i]);
puts("");
}
int main( )
{
int i, j, a, b, c, d, t;
debug( );
scanf("%d",&t);
while (t--)
{
scanf("%d%d%d",&P1,&N1,&M1);
init( );
/*
for (i = 2; i <= P1; i++)
{
Nd.x = i -1 ;
Nd.v = 0;
T[i].push_back(Nd);
}
*///不加也能A
for (i = 1; i <= N1; i++) {
scanf("%d%d%d", &a, &b, &d); // xb - xa <= d insert(a, b, d)
Nd.x = b, Nd.v = d;
T[a].push_back(Nd);
}
for (i = 1; i <= M1; i++) {
scanf("%d%d%d",&a, &b, &c); // xb- xa >= d xa- xb <= -d insert(b, a, -d)
Nd.x = a, Nd.v = -c;
T[b].push_back(Nd);
}
printf("%d\n",spfa( ));
//print(N);
}
return 0;
}
/*
题目要求的是求 最大值。即最短路 <=
d[j] < d[i] + map[i][j];
d[j] - d[i] < map[i][j]
xb - xa <= d
insert(i, j, d);
xb - xa >= d
xa - xb <= -d
最小值最长路 >=
d[j] > d[i] + map[i][j];
d[j] - d[i] > map[i][j]
insert(i, j, d);
差分约束系统(SPFA)
对于差分约束系统,建立的不等式是>=则在SPFA中求最长路。A-B>=C,则从B连一条权为C的边到A。
反之求最短路。A-B<=C,则从B连一条权为C的边到A。
注意两者对DIS初始化的不同
*/
World Exhibition
posted on 2011-08-06 07:59 more think, more gains 阅读(144) 评论(0) 编辑 收藏 举报