欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDU5521 Meeting【最短路】

程序员文章站 2022-05-22 14:34:03
...

题意:一张图,双向边,A在1节点,B在n节点,两人都能动,问他们最短的相遇时间,可以哪些点碰面。给了很多集合,集合内的点相互到达的时间为t


思路:给每个集合建一个点,集合内的点都连到这个点上,分别从A、B跑spfa,取每个点的两次最短距离的最大值,就是在这个点最短的遇见时间。巧妙建图,想不出QWQ


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e6+5;
ll d[maxn],d2[maxn];
int t[maxn],inq[maxn];
int ans[maxn],go;

struct Edge
{
	int to,next;
	ll val;
}edge[maxn*2];
int head[maxn],tot;

void add(int x,int y,ll val)
{
	edge[tot].to = y;
	edge[tot].val = val;
	edge[tot].next = head[x];
	head[x] = tot++;
}

void init(int x)
{
	memset(head,-1,sizeof head);
	tot = 0;
}

void spfa1(int x)
{
	queue<int> q;
	while(!q.empty())
		q.pop();
	memset(inq,0,sizeof inq);
	memset(d,0x3f,sizeof d);
	d[x] = 0;
	q.push(x);
	while(!q.empty())
	{
		int now = q.front();q.pop();
		inq[now] = 0;
		for(int i = head[now]; i != -1; i = edge[i].next)
		{
			int temp = edge[i].to;
			if(d[now] + edge[i].val < d[temp])
			{
				d[temp] = d[now] + edge[i].val;
				if(!inq[temp])
				{
					inq[temp] = 1;
					q.push(temp);
				}
			}
		}
	}
}

void spfa2(int x)
{
	queue<int> q;
	while(!q.empty())
		q.pop();
	memset(inq,0,sizeof inq);
	memset(d2,0x3f,sizeof d2);
	d2[x] = 0;
	q.push(x);
	while(!q.empty())
	{
		int now = q.front();q.pop();
		inq[now] = 0;
		for(int i = head[now]; i != -1; i = edge[i].next)
		{
			int temp = edge[i].to;
			if(d2[now] + edge[i].val < d2[temp])
			{
				d2[temp] = d2[now] + edge[i].val;
				if(!inq[temp])
				{
					inq[temp] = 1;
					q.push(temp);
				}
			}
		}
	}
}

int main(void)
{
	int n,m,T,kase = 1;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		init(n);
		for(int i = 1; i <= m; i++)
		{
			int tt,tp;
			ll val;
			scanf("%lld%d",&val,&tt);
			for(int j = 1; j <= tt; j++)
			{
				scanf("%d",&tp);
				add(tp,i+n,val);
				add(i+n,tp,val);
			}
		}
		spfa1(1);
		spfa2(n);
		ll time = 0x3f3f3f3f3f3f3f3f;
		go = 0;
		for(int i = 1; i <= n; i++)
		{
			if(max(d[i],d2[i]) < time)
			{
				time = max(d[i],d2[i]);
				go = 0;
				ans[go++] = i;
			}
			else if(max(d[i],d2[i]) == time && time != 0x3f3f3f3f3f3f3f3f)
			{
				ans[go++] = i;
			}
		}
		if(go == 0)
		{
			printf("Case #%d: Evil John\n",kase++);
			continue;
		}
		printf("Case #%d: %lld\n",kase++,time/2);
		for(int i = 0; i < go; i++)
		{
			printf("%d%c",ans[i],i == go-1?'\n':' ');
		}
	}
	return 0;
}


相关标签: 最短路