POJ 3169 Layout (差分约束)

21 篇文章 0 订阅

解题思路:很标准的差分约束题目,根据题意列出不等式,并将所有的不等式转化为 ≤ 形式,然后跑最短路即可。

AC代码:

/*
* @Author: wchhlbt
* @Last Modified time: 2017-09-19
*/

#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <limits>
#include <climits>
#include <cstdio>

#define Fori(x) for(int i=0;i<x;i++)
#define Forj(x) for(int j=0;j<x;j++)
#define maxn 10007
#define inf 0x3f3f3f3f
#define ONES(x) __builtin_popcount(x)
#define pb push_back
#define AA first
#define BB second
#define _  << "  " <<
using namespace std;

typedef long long ll ;
const double eps =1e-8;
const int mod = 998244353;
const double PI = acos(-1.0);
int dx[5] = {0,0,1,-1,0};
int dy[5] = {1,-1,0,0,0};
inline int read(){ int cnt;    scanf("%d",&cnt);   return cnt;}

//每次使用前需要调用init函数初始化 可以处理负权边
//最坏复杂度O(V*E)
int d[maxn],inq[maxn];//inq数组储存当前点是否在队列中
int deg[maxn];//记录每个节点入队次数
vector<pair<int,int> > e[maxn]; //pair<节点, 边权> 
int n;
void init()
{
	for(int i = 0; i<maxn; i++){
		e[i].clear();
		d[i] = inf;
		inq[i] = 0;
		deg[i] = 0;
	}
}
int SPFA(int s)//s为起点
{
	queue<int> Q;
	Q.push(s); d[s] = 0; inq[s] = 1; deg[s] = 1;
	while(!Q.empty()){
		int hd = Q.front();
		Q.pop();	inq[hd] = 0;	
		for(int i = 0; i<e[hd].size(); i++){
			int u = e[hd][i].first;
			int v = e[hd][i].second;
			if(d[u]>d[hd]+v){
				d[u] = d[hd] + v;
				if(inq[u]==1)	continue;
				inq[u] = 1;
				deg[u]++;
				if(deg[u]>=n)	return -1;
				Q.push(u);
			}
		}
	}
	if(d[n]==inf)	return -2;
	return d[n];
}


int main()
{
	int x,y;
	while(~scanf("%d%d%d",&n,&x,&y))
	{
		init();
		for(int i = 0; i<x; i++){
			int a,b,c;
			scanf("%d%d%d",&a,&b,&c);
			e[a].pb(make_pair(b,c));
			//e[b].pb(make_pair(a,c));
		}
		for(int i = 0; i<y; i++){
			int a,b,c;
			scanf("%d%d%d",&a,&b,&c);
			//e[a].pb(make_pair(b,-c));
			e[b].pb(make_pair(a,-c));
		}
		cout << SPFA(1) << endl;
	}
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值