CodeForces - 1486E Paired Payment(分层图最短路)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1486E Paired Payment(分层图最短路)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 nnn 個點 mmm 條邊組成的帶權無向圖,規(guī)定每次只能走兩條邊,假設走的兩條邊為 a?>b?>ca->b->ca?>b?>c,那么花費的權值為 (wab+wbc)2(w_{ab}+w_{bc})^2(wab?+wbc?)2,問從點 111 到 nnn 個點的最短路分別是多少,如果不可達輸出 ?1-1?1
題目分析:讀題的時候注意到了 www 的上限只有 505050,本來以為只是限制答案不爆 intintint 的,結果說是用來建分層圖的。。
首先本題中最后的答案一定是經(jīng)過偶數(shù)條邊到達的,所以自然需要先給距離數(shù)組 ddd 加一維用來維護奇偶,又因為 www 很小,可以直接用來記錄 preprepre,也就是上一條邊的權值
如此一來,當 “偶數(shù)” 轉移到 “奇數(shù)” 時,我們可以將邊權設置為 000 ,也就是隨意轉移,但是當從 “奇數(shù)” 轉移到 “偶數(shù)” 的時候,就需要利用題目中的公式配合 preprepre 計算貢獻了
代碼:
// Problem: E. Paired Payment // Contest: Codeforces - Codeforces Round #703 (Div. 2) // URL: https://codeforces.com/contest/1486/problem/E // Memory Limit: 512 MB // Time Limit: 4000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e5+100; vector<pair<int,int>>node[N]; int d[N][55][2]; bool vis[N][55][2]; struct Node {int to,val,pre,odds;bool operator<(const Node& t)const {return val>t.val;} }; void Dijkstra(int st) {memset(d,inf,sizeof(d));priority_queue<Node>q;d[st][0][0]=0;q.push({st,0,0,0});while(q.size()) {auto it=q.top();q.pop();int u=it.to,pre=it.pre,odds=it.odds;if(vis[u][pre][odds]) {continue;}vis[u][pre][odds]=true;for(auto it:node[u]) {int v=it.first,w=it.second,nw;if(odds&1) {nw=(w+pre)*(w+pre);} else {nw=0;}if(d[u][pre][odds]+nw<d[v][w][odds^1]) {d[v][w][odds^1]=d[u][pre][odds]+nw;q.push({v,d[v][w][odds^1],w,odds^1});}}} } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int n,m;read(n),read(m);while(m--) {int u,v,w;read(u),read(v),read(w);node[u].push_back({v,w});node[v].push_back({u,w});}Dijkstra(1);for(int i=1;i<=n;i++) {int ans=inf;for(int j=0;j<=50;j++) {ans=min(ans,d[i][j][0]);}if(ans==inf) {ans=-1;}printf("%d ",ans);}return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1486E Paired Payment(分层图最短路)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1486D M
- 下一篇: CodeForces - 1486F P