P2169 正则表达式

然而题目和正则表达式没一点关系

强连通分量,缩点,spfa

先缩点,然后跑最短路。

emmm,堆优化SPFA了解一下?

// luogu-judger-enable-o2
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<stack>
using namespace std;

int from[1000007],to[1000007],nex[1000007],val[1000007],head[200007];
int dfn[200007],low[200007],instack[200007],dfsnum,sccnum,belong[200007];
int dis[200007],inque[200007];
struct cmp{bool operator () (int &x,int &y){return dis[x]>dis[y];}};
priority_queue<int,vector<int>,cmp> q;
stack<int> s;

void tarjan(int u)
{
	dfn[u]=++dfsnum;
	low[u]=dfn[u];
	instack[u]=true;
	s.push(u);
	for(int i=head[u];i;i=nex[i])
	{
		if(!dfn[to[i]])
		{
			tarjan(to[i]);
			low[u]=min(low[u],low[to[i]]);
		}
		else if(instack[to[i]])
			low[u]=min(low[u],dfn[to[i]]);
	}
	if(dfn[u]==low[u])
	{
		int v;
		++sccnum;
		do
		{
			v=s.top();
			s.pop();
			belong[v]=sccnum;
			instack[v]=false;
		}while(u!=v);
	}
} 

void spfa(int s)
{
	int v;
	dis[s]=0;
	inque[s]=true;
	q.push(s);
	while(!q.empty())
	{
		v=q.top();
		q.pop();
		for(int i=head[v];i;i=nex[i])
		{
			if(dis[to[i]]>dis[v]+val[i])
			{
				dis[to[i]]=dis[v]+val[i];
				if(!inque[to[i]])
				{
					inque[to[i]]=true;
					q.push(to[i]);
				}
			}
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	int n,m,x,y,z;
	cin>>n>>m;
	memset(dis,0x7f,sizeof(dis));
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y>>z;
		from[i]=x;
		to[i]=y;
		val[i]=z;
		nex[i]=head[x];
		head[x]=i;
	}
	tarjan(1);
	for(int i=1;i<=m;i++)
		if(belong[from[i]]==belong[to[i]])
			val[i]=0;
	spfa(1);
	cout<<dis[n];
	return 0;
}
posted @ 2018-07-26 20:44  Coool  阅读(166)  评论(0编辑  收藏  举报