Layout POJ - 3169

版权声明: https://blog.csdn.net/weixin_40959045/article/details/79450262

题意:

       有的牛之间不能超过一定距离 有的牛之间不能小于一定距离 使第一头牛与最后一头牛距离最大

思路:

  1. 转化为最短路
  2. d[a]+ dml <= d[b]
  3. abs(d[a] - d[b]) >= dmd     d[a] >= d[b] + dmd  && (d[b] >= dmd + d[a] -> d [b]  - dmd >= d[a])
  4. 为求最大值 所以d[a] <= d[b] 故可不考虑 d[a] >= d[b] + dmd

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int MAX_V = 1005;
const int MAX_E = 30000;
const int  INF = 1<<30;
struct edge{
  int v;
  int cost;
  int next;
};
struct edge es[MAX_E];
int d[MAX_V],head[MAX_V];
bool inqueue[MAX_V];
int inq[MAX_V];
int V,len;
deque<int> q;
void add(int from,int to,int val)
{
    es[len].v=to;
    es[len].cost =val;
    es[len].next = head[from];
    head[from]=len++;
}
int spfa(int s){
  memset(inqueue,0,sizeof inqueue);
  memset(inq,0,sizeof inq);
  d[s] = 0; inqueue[s] = 1;
  inq[s]++;
  while(!q.empty()) q.pop_back();
  q.push_back(s);
  while (!q.empty()){
    int u = q.front(); q.pop_front();
    inqueue[u] = 0;
    for (int i = head[u];i != -1;i = es[i].next){
      int v = es[i].v;
      if (d[v] > d[u] + es[i].cost){
        d[v] = d[u] + es[i].cost;
        if (!inqueue[v]){
          inq[v]++;
          if (inq[v] > V) continue;
          if (!q.empty() && d[v] < d[q.front()])
            q.push_front(v);
          else
            q.push_back(v);
          inqueue[v] = 1;
        }
      }
    }
  }
  int res = d[V];
  if (d[V]<0){
    res = -1;
  } else if (res == INF){
    res = -2;
  }
  return res;
}

void init(){
  memset(head,-1,sizeof head);
  int ML,DL;
  scanf("%d%d%d",&V,&ML,&DL);
  fill(d,d+V+1,INF);
  for (int i = 0;i<ML;i++){
    int u,v,cost;
    scanf("%d%d%d",&u,&v,&cost);
    add(u,v,cost);
  }
  for (int i = 0;i<DL;i++){
    int u,v,cost;
    scanf("%d%d%d",&u,&v,&cost);
    add(v,u,-cost);
  }
  for (int i = 1;i<V;i++)
    add(i+1,i,0);
}
int main()
{
  init();
  printf("%d\n",spfa(1));
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40959045/article/details/79450262