标签:cpp ace sizeof 差分约束 ++ pen amp size cto
知道差分约束的都知道,这是一道线性差分约束裸题
对于ml的数据我们有,dis[y] - dis[x] <= w,于是这里建立边 x -> y,value = w
对于md的数据我们有,dis[y] - dis[x] >= w,变形dis[x] - dis[y] <= -w,建立边 y -> x,value = -1
由于题目有限制条件,两头牛可以放在一起,并且编号小的放在前面,有 dis[i + 1] - dis[i] >= 0,变形dis[i] - dis[i + 1] <= 0,建立边 i + 1 -> i,value = 0
Powered by CK 2020:04:07
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10;
int head[N], to[N], nex[N], value[N], cnt;
int visit[N], dis[N], num[N], n, ml, md;
void add(int x, int y, int w) {
to[cnt] = y;
value[cnt] = w;
nex[cnt] = head[x];
head[x] = cnt++;
}
int spfa() {
memset(dis, 0x3f, sizeof dis);
memset(visit, 0, sizeof visit);
memset(num, 0, sizeof num);
queue<int> q;
q.push(1);
dis[1] = 0;
visit[1] = 1, num[1] = 1;
while(!q.empty()) {
int temp = q.front();
q.pop();
visit[temp] = 0;
for(int i = head[temp]; i; i = nex[i]) {
if(dis[to[i]] > dis[temp] + value[i]) {
dis[to[i]] = dis[temp] + value[i];
if(++num[to[i]] == n) return -1;
q.push(to[i]);
visit[to[i]] = 1;
}
}
}
return dis[n] == INF ? -2 : dis[n];
}
int main() {
// freopen("in.txt", "r", stdin);
int x, y, w;
while(scanf("%d %d %d", &n, &ml, &md) != EOF) {
memset(head, 0, sizeof head);
cnt = 1;
for(int i = 0; i < ml; i++) {
scanf("%d %d %d", &x, &y, &w);
add(x, y, w);
}
for(int i = 0; i < md; i++) {
scanf("%d %d %d", &x, &y, &w);
add(y, x, -w);
}
for(int i = 1; i < n; i++)
add(i + 1, i, 0);
printf("%d\n", spfa());
}
return 0;
}
标签:cpp ace sizeof 差分约束 ++ pen amp size cto
原文地址:https://www.cnblogs.com/lifehappy/p/12654825.html