求助
查看原帖
求助
189342
Mr_Greeper楼主2020/5/3 20:10

RT 代码如下,TLE三个点,求优化方案

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int sum,ans=-1,head[100000],f,t,v,n,m,top,dis[1000000],k;
bool vis[100000];
struct edge
{
	int f,t,v,n;
}e[1000000];
struct gl
{
	int i;
	int sum;
}poi;
int read()
{
	char ch=getchar();
	int flag=1;
	int ans=0;
	while(ch<'0'||ch>'9')
	{
		if(ch=='-')flag=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
	{
		ans=(ans<<3)+(ans<<1)+ch-'0';
		ch=getchar();
	}
	return ans*flag;
}
bool operator < (gl a,gl b)
{
	return a.sum>b.sum;
}
priority_queue < gl > q;
int Dijstra()
{
	memset(vis,0,sizeof(vis));
	poi.i=1;
	poi.sum=0;
	q.push(poi);
	for(int i=1;i<=n;i++)dis[i]=2147483647;
	dis[1]=0;
	while(!q.empty())
	{
		k=q.top().i;
		q.pop();
		if(vis[k])continue;
		vis[k]=1;
		for(int i=head[k];i;i=e[i].n)
		{
			
			if(dis[e[i].t]>dis[k]+e[i].v)
			{
				dis[e[i].t]=dis[k]+e[i].v;
				poi.i=e[i].t;
				poi.sum=dis[e[i].t];
				q.push(poi);
			}
		}
	}
	return dis[n];
}
void search(int k)
{
	if(k>m*2)return;
	e[k].v*=2;
	e[k*2].v*=2;
	int now=Dijstra();
	ans=max(now,ans);
	e[k].v/=2;
	e[k*2].v/=2;
	search(k+1);
}
void add_edge(int f,int t,int v)
{
	top++;
	e[top].f=f;
	e[top].t=t;
	e[top].v=v;
	e[top].n=head[f];
	head[f]=top;
}
int main()
{
	n=read();
	m=read();
	for(int i=1;i<=m;i++)
	{
		f=read();
		t=read();
		v=read();
		add_edge(f,t,v);
		add_edge(t,f,v);
	}
	sum=Dijstra();
	search(1);
	cout<<ans-sum;
	return 0;
} 
2020/5/3 20:10
加载中...