题目链接
分析
这是一道简单的差分约束的题目,关于差分约束,这个blog写的很好
设
ti
表示第i条指令完成的最短时间,那麽对于一个约束
x,y,z
有
ty−txtx−ty≥z≤z
这不就是差分约束的标准形式吗,要求完成的最短时间,则有
maxti−mintj+1
Ac code
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define PI acos(-1)
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define INF64 0x3f3f3f3f3f3f3f3f
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define ms(x,v) memset((x),(v),sizeof(x))
#define scint(x) scanf("%d",&x );
#define scf(x) scanf("%lf",&x );
#define eps 1e-10
#define dcmp(x) (fabs(x) < eps? 0:((x) <0?-1:1))
#define lc o<<1
#define rc o<<1|1
using namespace std;
typedef long long LL;
typedef long double DB;
typedef pair<int,int> Pair;
const int maxn = 10000+10;
const int MAX_V = 1000+10;
int ne,nv;
struct Edge{
int from,to,weight;
Edge(int u=0,int v=0,int w=0):from(u),to(v),weight(w){};
};
int tot=0;
Edge E[maxn*2];
std::vector<int> G[MAX_V];
int dist[MAX_V];
void add_edge(int u,int v,int w){
E[tot++] = Edge{u,v,w};
G[u].push_back(tot-1);
}
void dijkstra(int s){
priority_queue<Pair,std::vector<Pair> > pq;
memset(dist,INF,sizeof(dist));
pq.push(Pair(0,s));
dist[s] = 0;
while (!pq.empty()) {
Pair p = pq.top();pq.pop();
int d = p.fi,u = p.se;
if(dist[u]<d)continue;
for(int i=0 ; i<G[u].size() ; ++i)
{
int e = G[u][i];
int v = E[e].to;
if(dist[v]>dist[u]+E[e].weight){
dist[v] = dist[u]+E[e].weight;
pq.push(Pair(dist[v],v));
}
}
}
}
int deg[MAX_V];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,m;
while (cin>>n>>m) {
for(int i=0 ; i<=n ; ++i)G[i].clear();
tot =0;
ms(deg,0);
while (m--) {
int u,v,w;
cin>>u>>v>>w;
add_edge(v+1,u+1,-w);
deg[u+1]++;
}
for(int i=1 ; i<=n ; ++i){
if(deg[i] ==0)add_edge(0,i,0);
}
dijkstra(0);
int ma = *max_element(dist+1,dist+n+1);
int mi = *min_element(dist+1,dist+n+1);
std::cout << ma-mi +1 << '\n';
}
//std::cout << "time "<< clock()/1000 <<"ms"<< '\n';
return 0;
}