1. 程式人生 > 實用技巧 >CodeForces - 715B

CodeForces - 715B

CodeForces - 715B
先判斷impossible的情況
1. 0邊全賦值為1,此時最短路>L
2. 0邊全賦值為inf,此時最短路<L

我們按讀入順序對0邊進行排列,然後我們二分找到第一個必經0邊,假設它在0邊中的下標是第i個,那麼1~i的0邊為1,i+1~cnt的0邊為inf(就是這些邊不走),
最後把這個必經邊設成合法值就可以了,複雜度就是跑16次spfa

#include <bits/stdc++.h>
#define inf 2333333333333333
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)
//
by war //2020.8.21 using namespace std; long long n,m,L,s,t,x,y,cnt,l,r,mid; long long w[N],d[N],E[N]; bool vis[N]; deque<long long>q; struct node{ long long n; long long id; node *next; }*e[N]; struct Node{ long long x; long long y; }c[N]; void in(long long &x){ long
long y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } void o(long long x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } void push(long long x,long
long y,long long id){ node *p; p=new node(); p->n=y; p->id=id; if(e[x]==0) e[x]=p; else{ p->next=e[x]->next; e[x]->next=p; } } void spfa(){ For(i,1,n) d[i]=inf,vis[i]=0; d[s]=0; q.push_front(s); while(!q.empty()){ x=q.front();q.pop_front(); vis[x]=1; for(node *i=e[x];i;i=i->next){ if(d[i->n]>d[x]+w[i->id]){ d[i->n]=d[x]+w[i->id]; if(!vis[i->n]){ vis[i->n]=1; if(!q.empty() && d[i->n]<d[q.front()]) q.push_front(i->n); else q.push_back(i->n); } } } vis[x]=0; } } bool check(long long x){ For(i,1,x) w[E[i]]=1; For(i,x+1,cnt) w[E[i]]=inf; spfa(); return d[t]<=L; } signed main(){ in(n);in(m);in(L);in(s);in(t); s++;t++; For(i,1,m){ in(x);in(y);in(w[i]); c[i].x=x;c[i].y=y; x++;y++; push(x,y,i); push(y,x,i); if(!w[i]) E[++cnt]=i; } For(i,1,cnt) w[E[i]]=inf; spfa(); if(d[t]<L){ puts("NO"); return 0; } For(i,1,cnt) w[E[i]]=1; spfa(); if(d[t]>L){ puts("NO"); return 0; } l=1;r=cnt; while(l<r){ mid=(l+r)>>1; if(check(mid)) r=mid; else l=mid+1; } check(l); w[E[l]]=L-d[t]+1; puts("YES"); For(i,1,m){ o(c[i].x);p(' ');o(c[i].y);p(' ');o(w[i]);p('\n'); } return 0; }