이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template<class T> bool cmin(T &i, T j) { return i > j ? i=j,true:false; }
template<class T> bool cmax(T &i, T j) { return i < j ? i=j,true:false; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
int tot_nodes = 0;
vector<map<int,vector<pair<int,int>>>> g_adj(n);
for (int i=0,u,v,c,w;i<m;i++) {
cin >> u >> v >> c >> w;
--u,--v;
g_adj[u][c].emplace_back(v,w);
g_adj[v][c].emplace_back(u,w);
}
map<pair<int,int>,int> mapping;
for (int i=0;i<n;i++) {
//cout << "node " << i << " with no color = " << tot_nodes << endl;
mapping[make_pair(i,-1)]=tot_nodes++;
for (auto &c: g_adj[i]) {
//cout << "node " << i << " with color " << c.first << " = " <<tot_nodes << endl;
mapping[make_pair(i,c.first)]=tot_nodes++;
}
}
const ll inf = 1e18;
vector<ll> dist(tot_nodes,inf);
vector<ll> last(tot_nodes,-inf);
vector<vector<tuple<int,int,int>>> adj(tot_nodes);
vector<int> color(tot_nodes);
auto add_edge = [&](int u,int v,int c,int w) {
//cout<<"added edge "<<u<<" "<<v<<endl;
adj[u].emplace_back(v,c,w);
};
vector<map<int,ll>> tot_cost(tot_nodes);
int lst=0;
for (int i=0;i<n;i++) {
int u = mapping[make_pair(i,-1)]; // general node
color[u] = -1;
if (i == n-1) { lst = u; }
for (auto &c: g_adj[i]) {
int u2 = mapping[make_pair(i,c.first)]; // color_node
color[u2]=c.first;
for (auto &[j,w]: c.second) {
tot_cost[u][c.first]+=w;
tot_cost[u2][c.first]+=w;
int v = mapping[make_pair(j,-1)];
int v2 = mapping[make_pair(j,c.first)];
add_edge(u,v,c.first,w);
add_edge(u,v2,c.first,w);
add_edge(u2,v,c.first,w);
add_edge(u2,v2,c.first,w);
}
}
}
dist[0] = 0;
set<pair<ll,int>> q;
q.emplace(0,0);
while(!q.empty()) {
int x=(*q.begin()).second;q.erase(q.begin());
if (color[x]==-1) {
for (auto &[y,c,w]: adj[x]) {
if (color[y]==-1) {
ll ww=min((ll)w,tot_cost[x][c]-w);
ll p=dist[y];
if (cmin(dist[y],dist[x]+ww)) {
q.erase(make_pair(p,y));
q.emplace(dist[y],y);
}
} else {
ll p=dist[y];
if (cmin(dist[y],dist[x]+w)) {
last[y]=w;
q.erase(make_pair(p,y));
q.emplace(dist[y],y);
}
}
//cout<<"w = "<<w<<endl;
//cout<<"from "<<x<<" to "<<y<<" "<<dist[y]<<endl;
}
} else {
for (auto &[y,c,w]: adj[x]) {
if (color[y]==-1) {
ll ww=min((ll)w,tot_cost[x][color[x]]-last[x]-w);
ll p=dist[y];
if (cmin(dist[y],dist[x]+ww)) {
q.erase(make_pair(p,y));
q.emplace(dist[y],y);
}
} else {
ll p=dist[y];
if (cmin(dist[y],dist[x]+w)) {
last[y]=w;
q.erase(make_pair(p,y));
q.emplace(dist[y],y);
}
}
//cout<<"from "<<x<<" to "<<y<<" "<<dist[y]<<endl;
}
}
}
cout << (dist[lst]==inf?-1:dist[lst]) << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |