维护一个sum[]:最短路径中以i结尾的连续小路的长度和
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const int N = 510;
const int M = 2e5+10;
struct node
{
int p;
ll w;
node(){}
node(int _p, ll _w):p(_p),w(_w){}
bool operator <(const node &a)const
{
return w>a.w;
}
};
bool vis[N];
ll dis[N];
ll sum[N];//最短路径中以i结尾的连续小路的长度和
int to[M],type[M],nxt[M];
ll val[M];
int head[N],tot;
int n, m;
void addedge(int u, int v, int t, int w)
{
++tot;
to[tot] = v;
type[tot] = t;
val[tot] = w;
nxt[tot] = head[u];
head[u] = tot;
}
void dijkstra(int s)
{
priority_queue <node> q;
memset(vis, 0, sizeof(vis));
memset(sum, 0, sizeof(sum));
for(int i = 1; i <= n; ++i) dis[i] = INF;
dis[s] = 0;
q.push(node(s, 0));
while(!q.empty())
{
node u = q.top();
q.pop();
int p = u.p;
if(vis[p]) continue;
vis[p] = 1;
for(int i = head[p]; ~i; i = nxt[i])
{
int v = to[i];
if(vis[v]) continue;
ll cost = 0;
if(type[i])
{
ll tmp = sum[p]+val[i];
cost = dis[p]-sum[p]*sum[p]+tmp*tmp;
}
else cost = dis[p]+val[i];
if(cost<dis[v])
{
dis[v] = cost;
if(type[i])
sum[v] = sum[p]+val[i];
else sum[v] = 0;
q.push(node(v, dis[v]));
}
}
}
}
int main()
{
scanf("%d %d", &n, &m);
memset(head, -1, sizeof(head));
tot = 0;
while(m--)
{
int t, u, v, w;
scanf("%d %d %d %d", &t, &u, &v, &w);
addedge(u, v, t, w);
addedge(v, u, t, w);
}
dijkstra(1);
printf("%lld\n", dis[n]);
return 0;
}