HDU 1534 Schedule Problem(差分约束)

题意:一个项目可以分为几个部分。 每个部分都应连续完成。 这意味着如果一个零件需要3天,我们应该连续3天完成它。 这些部分中有四种约束,分别是FAS,FAF,SAF和SAS。 如果第一个零件应该在第二个零件开始之后完成,则零件之间的约束就是FAS。FAF完成后完成。 SAF完成后启动,SAS启动后启动。 假设有足够的人参与项目,这意味着我们可以同时进行任何数量的部分。 编写一个程序给出项目的时间表,该时间表最短。

题解:差分约束
d [ i ] d[i] d[i]表示第 i i i个部分开始的时间,依据题意建立约束即可,用spfa跑最长路。

注意每个点开始的时间都可以是0,因为不可能为负。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
#define pii pair<int, int>
using namespace std;
const int maxn = 11111;
int n, t[maxn], x, y;
string s;
struct node {
    
    
    int v, nxt, w;
}edge[maxn << 2];
int vis[maxn], d[maxn], head[maxn], mark[maxn], k;
void add(int u, int v, int w) {
    
    
    edge[++k].nxt = head[u];
    edge[k].v = v;
    edge[k].w = w;
    head[u] = k;
}
bool spfa() {
    
    
    queue<int>q;
    for (int i = 1; i <= n; i++) {
    
    
        d[i] = 0;
        vis[i] = mark[i] = 0;
        q.push(i);
    }
    //q.push(1);
    //mark[1] = vis[1] = 1;
    //d[1] = 0;
    while (!q.empty()) {
    
    
        int u = q.front(); q.pop();
        vis[u] = 0;
        for (int i = head[u]; i; i = edge[i].nxt) {
    
    
            int v = edge[i].v, w = edge[i].w;
            if (d[v] < d[u] + w) {
    
    
                d[v] = d[u] + w;
                if (vis[v]) continue;
                vis[v] = 1;
                if(++mark[v] > n) return false;  //负环
                q.push(v);
            }
        }
    }
    return true;
}
int main() {
    
    
    int cas = 0;
	while (~scanf("%d", &n) && n) {
    
    
        k = 0;
        memset(head, 0, sizeof(head));
		for (int i = 1; i <= n; i++) scanf("%d", &t[i]);
		while (cin >> s && s != "#") {
    
    
			scanf("%d%d", &x, &y);
            if (s == "FAF") {
    
    
                add(y, x, t[y] - t[x]);
            }
            else if (s == "FAS") {
    
    
                add(y, x, -t[x]);
            }
            else if (s == "SAF") {
    
    
                add(y, x, t[y]);
            }
            else {
    
    
                add(y, x, 0);
            }
		}
        printf("Case %d:\n", ++cas);
        if (!spfa()) {
    
    
            puts("impossible");
            puts("");
        }
        else {
    
    
            for (int i = 1; i <= n; i++) {
    
    
                printf("%d %d\n", i, d[i]);
            }
            puts("");
        }
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43680965/article/details/108742794