World Exhibition
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1754 Accepted Submission(s): 886
Problem Description
There is something interesting. Some like each other and want to be within a certain distance of each other in line. Some really dislike each other and want to be separated by at least a certain distance. A list of X (1 <= X <= 10,000) constraints describes which person like each other and the maximum distance by which they may be separated; a subsequent list of Y constraints (1 <= Y <= 10,000) tells which person dislike each other and the minimum distance by which they must be separated.
Your job is to compute, if possible, the maximum possible distance between person 1 and person N that satisfies the distance constraints.
Input
The next line: Three space-separated integers: N, X, and Y.
The next X lines: Each line contains three space-separated positive integers: A, B, and C, with 1 <= A < B <= N. Person A and B must be at most C (1 <= C <= 1,000,000) apart.
The next Y lines: Each line contains three space-separated positive integers: A, B, and C, with 1 <= A < B <= C. Person A and B must be at least C (1 <= C <= 1,000,000) apart.
Output
Sample Input
4 2 1
1 3 8
2 4 15
2 3 4
Sample Output
Author
Source
//2017-08-29
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack> using namespace std; const int N = ;
const int M = ;
const int INF = 0x3f3f3f3f; int head[N], tot;
struct Edge{
int to, next, w;
}edge[M]; void init(){
tot = ;
memset(head, -, sizeof(head));
} void add_edge(int u, int v, int w){
edge[tot].w = w;
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
} int n, m, c;
bool vis[N];
int dis[N], cnt[N]; bool spfa(int s, int n){
memset(vis, , sizeof(vis));
memset(dis, INF, sizeof(dis));
memset(cnt, , sizeof(cnt));
vis[s] = ;
dis[s] = ;
cnt[s] = ;
deque<int> dq;
dq.push_back(s);
int sum = , len = ;
while(!dq.empty()){
// LLL 优化
while(dis[dq.front()]*len > sum){
dq.push_back(dq.front());
dq.pop_front();
}
int u = dq.front();
sum -= dis[u];
len--;
dq.pop_front();
vis[u] = ;
for(int i = head[u]; i != -; i = edge[i].next){
int v = edge[i].to;
if(dis[v] > dis[u] + edge[i].w){
dis[v] = dis[u] + edge[i].w;
if(!vis[v]){
vis[v] = ;
// SLF 优化
if(!dq.empty() && dis[v] < dis[dq.front()])
dq.push_front(v);
else dq.push_back(v);
sum += dis[v];
len++;
if(++cnt[v] > n)return false;
}
}
}
}
return true;
} int main()
{
std::ios::sync_with_stdio(false);
//freopen("input.txt", "r", stdin);
int T, n, x, y;
cin>>T;
while(T--){
init();
cin>>n>>x>>y;
int u, v, w;
while(x--){
cin>>u>>v>>w;
add_edge(u, v, w);
}
while(y--){
cin>>u>>v>>w;
add_edge(v, u, -w);
}
if(spfa(, n)){
if(dis[n] == INF)cout<<-<<endl;
else cout<<dis[n]<<endl;
}else cout<<-<<endl;
} return ;
}