Challenges Programming Contest: Layout

Subject to the effect

Here Insert Picture Description

Problem-solving ideas

Given inequalities and claim wherein the difference between the two elements (such as the C-Amaximum). This is equivalent to seeking the shortest path problem. Because no one A C A\to C road corresponds withthe one or more inequalityimplied regardingC-Aconstraints. DETAILED understood that shown below:
from https://www.cnblogs.com/genius777/p/9163103.htmlGeneral solving steps:

  • (1) Construction FIG: The shape of each A V d A - V \ leq d inequality, a configuration V A V \to A , the length of d d directed edge.
  • (2) Find the C-Amaximum value is the shortest path from A to C
  • (3) If a negative ring, no solution. (There are no negative shortest ring)
  • (3) If it is INF, if any. (I.e., C-Athe maximum value infinite)

Code

#include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
const int MAX = 1005;
const int MAXE = 10000*2+5;
const int inf = 1<<20;
struct Edge
{
    int s;
    int t;
    int w;
}G[MAXE];
int d[MAX];
int N, ML, MD;
int cnt;
int bemft(int v)
{
    for(int i=0; i<=N; i++)
        d[i] = inf;
    d[v] = 0;
    for(int i=1; i<=N; i++)
    {
        int update = 0;
        for(int e=0; e<cnt; e++)
        {
            int from = G[e].s;
            int to = G[e].t;
            int cost = G[e].w;
            if(d[to] > d[from] + cost)
            {
                d[to] = d[from] + cost;
                update = 1;
            }
        }
        if(!update)
        {
            if(d[N] == inf)
                return -2;
            return d[N];
        }
        if(i >= N-1)
            return -1;
    }
}
int main()
{
    cnt = 0;
    scanf("%d%d%d", &N, &ML, &MD);
    for(int i=1; i<=N-1; i++)
    {
        G[cnt].s = i+1;
        G[cnt].t = i;  // d[i+1] >= d[i]   --> d[i+1] + 0 >= d[i]
        G[cnt++].w = 0;
    }

    int a, b, w;
    while(ML--)
    {
        scanf("%d%d%d", &a, &b, &w); // d[b] - d[a] <= w   --> d[b] <= w + d[a]
        G[cnt].s = a;
        G[cnt].t = b;
        G[cnt++].w = w;
    }
    while(MD--)
    {
        scanf("%d%d%d", &a, &b, &w);  // d[b] - d[a] >= w  --> d[b] - w >= d[a]
        G[cnt].s = b;
        G[cnt].t = a;
        G[cnt++].w = -w;
    }
    int ans = bemft(1);

    cout << ans << endl;
    return 0;
}

Knowledge Point

  • Bellman Ford algorithm if there is no negative ring, update most |V|-1times.
  • Keep in mind the difference between the conversion restraint system and the shortest. Comprising (1) Composition (2) is the maximum value for the most differencing short circuit. (3) the Bellman Ford algorithm is stored sides, not adjacent table.

Guess you like

Origin blog.csdn.net/Wangpeiyi9979/article/details/93708883