AcWing 3772. 更新线路(建反图+最短路计数)

传送门

视频讲解


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)
const int maxn=2e5+100;

int h[maxn],e[maxn],ne[maxn],idx;
int n,m,k,p[maxn];

void add(int u,int v){
	e[idx]=v,ne[idx]=h[u],h[u]=idx++;
}

int dis[maxn],cnt[maxn];

void bfs(int s){
	queue<int>q;
	memset(dis,0x3f,sizeof dis);
	q.push(s);dis[s]=0;
	while(!q.empty()){
		int t=q.front();q.pop();
		for(int i=h[t];~i;i=ne[i]){
			int j=e[i];
			if(dis[j]>dis[t]+1){
				dis[j]=dis[t]+1;q.push(j);
				cnt[j]=1;
			}
			else if(dis[j]==dis[t]+1) cnt[j]++;
		}
	}
}

int main(){
	memset(h,-1,sizeof h);
	n=read,m=read;
	rep(i,1,m){
		int u=read,v=read;
		add(v,u);
	}	
	k=read;
	rep(i,1,k) p[i]=read;
	bfs(p[k]);
	int minn=0,maxx=0;
	rep(i,1,k-1){
		if(dis[p[i]]<dis[p[i+1]]+1){
			minn++,maxx++;
		}
		else if(cnt[p[i]]>1) maxx++;
		
	}
	cout<<minn<<" "<<maxx<<"
";
	return 0;
}












原文地址:https://www.cnblogs.com/OvOq/p/15026470.html