Missile Silos CodeForces - 144D

原题链接
考察:dijkstra
思路:
可以证明一定不存在dist[u]+w1(w1>w/2) = d(该点离v更近.)的情况.
Missile Silos CodeForces - 144D

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1e5+10;
typedef pair<int,int> PII;
int n,m,s,h[N],idx,dist[N],st[N],ans,d,cnt;
struct Road{
	int fr,to,ne,w;
}road[N];
struct Path{
	int fr,to,w;
}path[N];
void add(int a,int b,int w)
{
	road[idx].w = w,road[idx].fr = a,road[idx].to = b,road[idx].ne = h[a],h[a]= idx++;
}
void dijkstra()
{
	memset(dist,0x3f,sizeof dist);
	priority_queue<PII,vector<PII>,greater<PII> > q;
	dist[s] = 0;
	q.push({0,s});
	while(q.size())
	{
		PII it = q.top();
		q.pop();
		int w = it.first,u = it.second;
		if(st[u]) continue;
		st[u] = 1;
		for(int i=h[u];i!=-1;i=road[i].ne)
		{
			int v = road[i].to;
			if(dist[v]>w+road[i].w)
			{
				dist[v] = w+road[i].w;
				q.push({dist[v],v});
			}
		}
	}
}
int main()
{
	scanf("%d%d%d",&n,&m,&s);
	memset(h,-1,sizeof h);
	for(int i=1;i<=m;i++)
	{
		int a,b,c; scanf("%d%d%d",&a,&b,&c);
		add(a,b,c); add(b,a,c);
		path[i].fr = a,path[i].w = c,path[i].to = b;
	}
	dijkstra();
	scanf("%d",&d);
	for(int i=1;i<=n;i++) if(dist[i]==d) ans++;
	for(int i=1;i<=m;i++)
	{
		int u = path[i].fr,v = path[i].to,w = path[i].w;
		if(dist[u]>=d&&dist[v]>=d) continue;
		if(dist[u]>=d&&dist[v]<d) 
		  if(dist[v]+w>d) ans++;
		if(dist[v]>=d&&dist[u]<d)
		  if(dist[u]+w>d) ans++; 
		if(dist[v]<d&&dist[u]<d)
		{
			if(dist[u]+dist[v]+w==2*d) ans++;
			else if(dist[u]+dist[v]+w>2*d) ans+=2; 
		}
	}
	printf("%d\n",ans);
	return 0;
}
上一篇:P1273 有线电视网


下一篇:[CF1468J] Road Reform - 最小生成树