/*
* @Author: RMQuan
* @Date: 2025-09-29 22:50:45
* @Last Modified by: RMQuan
* @Last Modified time: 2025-09-30 02:30:55
*/
/*idea :
*/
#include <bits/stdc++.h>
bool M1;
#define int long long
#define ll long long
#define fi first
#define se second
#define memfull(a,b) memset(a,b,sizeof(a));
#define endl '\n'
#define file(a) freopen(a".inp","r",stdin); freopen(a".out","w",stdout);
using namespace std;
const int MOD=1e9+7;
const int maxn=2e5+7;
const int inf=1e18;
struct canh {
int u,v,w,col;
};
vector<canh> adj[maxn];
int n,m;
unordered_map<int,long long> dis[maxn];
unordered_map<int,bool> vst[maxn];
unordered_map<int,int> cnt[maxn];
unordered_map<int,long long> psum[maxn];
struct node {
int u,prev_col,dist;
};
struct cmp {
bool operator()(const node &x,const node &y)const{
return x.dist>y.dist;
}
};
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for (int i=1;i<=m;i++)
{
int u,v,col,w;
cin>>u>>v>>col>>w;
adj[u].push_back({u,v,w,col});
adj[v].push_back({v,u,w,col});
psum[u][col]+=w;
psum[v][col]+=w;
cnt[u][col]++;
cnt[v][col]++;
}
priority_queue<node,vector<node>,cmp> q;
dis[1][-1]=0;
q.push({1,-1,0});
while (!q.empty())
{
int u=q.top().u;
int col=q.top().prev_col;
long long du=q.top().dist;
q.pop();
if (vst[u][col]) continue;
vst[u][col]=true;
if (col==-1)
{
for (auto &e:adj[u])
{
int v=e.v, c=e.col, w=e.w;
if (cnt[u][c]<=1)
{
if (!dis[v].count(-1) || dis[v][-1]>du)
{
dis[v][-1]=du;
q.push({v,-1,du});
}
}
else
{
if (!dis[v].count(c) || dis[v][c]>du)
{
dis[v][c]=du;
q.push({v,c,du});
}
if (!dis[v].count(-1) || dis[v][-1]>du+w)
{
dis[v][-1]=du+w;
q.push({v,-1,dis[v][-1]});
}
if (!dis[v].count(-1) || dis[v][-1]>du+psum[u][c]-w)
{
dis[v][-1]=du+psum[u][c]-w;
q.push({v,-1,dis[v][-1]});
}
}
}
}
else
{
for (auto &e:adj[u])
{
int v=e.v,c=e.col,w=e.w;
if (c==col)
{
long long cost=du+psum[u][c]-w;
if (!dis[v].count(-1) || dis[v][-1]>cost)
{
dis[v][-1]=cost;
q.push({v,-1,cost});
}
}
}
}
}
cout<<(dis[n].count(-1)?dis[n][-1]:-1);
bool M2;
cerr<<"-------------------------------------------------"<<endl;
cerr<<"Time : "<<clock()<<" ms"<<endl;
cerr<<"Memory : "<<abs(&M2-&M1)/1024/1024<<" MB"<<endl;
cerr<<"-------------------------------------------------"<<endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |