zoukankan      html  css  js  c++  java
  • Codeforces 938D Buy a Ticket 【spfa优化】

    用到了网络流的思想(大概)。新建一个源点s,所有边权扩大两倍,然后所有的点向s连边权为点权的无向边,然后以s为起点跑spfa(S什么L优化的),这样每个点到s的距离就是答案。
    原因的话,考虑答案应该是min(2*dis[i][j]+a[j]} ),那么每个点到s的距离就是若干条边边权的二倍加上某个点的点权,并且这个组合是最小的。证毕。

    #include<iostream>
    #include<cstdio>
    #include<queue>
    using namespace std;
    const int N=1000005;
    const long long inf=1e18;
    int n,m,s,h[N],cnt;
    long long a[N],dis[N];
    bool v[N];
    struct qwe
    {
    	int ne,to;
    	long long va;
    }e[N*10];
    int read()
    {
    	int r=0,f=1;
    	char p=getchar();
    	while(p>'9'||p<'0')
    	{
    		if(p=='-')
    			f=-1;
    		p=getchar();
    	}
    	while(p>='0'&&p<='9')
    	{
    		r=r*10+p-48;
    		p=getchar();
    	}
    	return r*f;
    }
    void add(int u,int v,long long w)
    {
    	cnt++;
    	e[cnt].ne=h[u];
    	e[cnt].to=v;
    	e[cnt].va=w;
    	h[u]=cnt;
    }
    int main()
    {
    	n=read(),m=read();
    	s=n+1;
    	for(int i=1;i<=m;i++)
    	{
    		int u=read(),v=read();
    		long long w;
    		scanf("%I64d",&w);
    		add(u,v,w*2);
    		add(v,u,w*2);
    	}
    	for(int i=1;i<=n;i++)
    	{
    		scanf("%I64d",&a[i]);
    		add(s,i,a[i]);
    		add(i,s,a[i]);
    	}
    	deque<int>q;
    	for(int i=1;i<=n+1;i++)
    		dis[i]=inf;
    	dis[s]=0;
    	v[s]=1;
    	q.push_back(s);
    	while(!q.empty())
    	{
    		int u=q.front();
    		q.pop_front();
    		v[u]=0;
    		for(int i=h[u];i;i=e[i].ne)
    			if(dis[e[i].to]>dis[u]+e[i].va)
    			{
    				dis[e[i].to]=dis[u]+e[i].va;
    				if(!v[e[i].to])
    				{
    					v[e[i].to]=1;
    					if(!q.empty()&&dis[e[i].to]<dis[q.front()])
    						q.push_front(e[i].to);
    					else
    						q.push_back(e[i].to);
    					
    				}
    			}
    	}
    	for(int i=1;i<=n;i++)
    		printf("%I64d ",dis[i]);
    	return 0;
    }
    
  • 相关阅读:
    Nginx使用
    MySQL 分区
    php PDO预处理
    php
    php
    linux 下编译安装MySQL
    php 工厂模式
    MySQL 权限管理
    hadoop集群安装20181016(20111130:前面太忙,没有写完,后面继续)
    JavaScript函数参数翻转——连接多个数组——zip、zipwith
  • 原文地址:https://www.cnblogs.com/lokiii/p/8452236.html
Copyright © 2011-2022 走看看