为什么最后要那么取模?
查看原帖
为什么最后要那么取模?
856309
oiyang楼主2023/7/6 16:45

前面直接输出tempans然后WA了,看了题解才知道要这么取模

#include <bits/stdc++.h>
using namespace std;
int n,m;
const int mod=1e9+7;
const int maxnode=1e5+5;
const int maxline=2e5+5;
int head[maxnode],k;
struct edge{int to,pre,w;}line[maxline*2];
void addline(int u,int v,int w)
{
	k++;
	line[k].to=v;
	line[k].pre=head[u];
	line[k].w=w;
	head[u]=k;
}
struct node
{
	int pos;
	long long d;
	friend bool operator <(const node &x,const node &y)
	{
		return x.d>y.d;
	}
};
priority_queue<node>q;


long long dis1[maxnode],dis2[maxnode];
long long tot1[maxnode],tot2[maxnode];
bool vis[maxnode];

void dij(int num,long long disa[],long long totb[])
{
	totb[num]=1;
	disa[num]=0;
	q.push((node){num,0});
	while(!q.empty())
	{
		node top=q.top();
		q.pop();
		int tempops=top.pos;
		if(vis[tempops])
			continue;
		vis[tempops]=1;
		for(int i=head[tempops];i;i=line[i].pre)
		{
			int v=line[i].to;
			if(disa[v]>disa[tempops]+line[i].w && !vis[v])
			{
				disa[v]=disa[tempops]+line[i].w;
				totb[v]=totb[tempops];
				q.push((node){v,disa[v]});
			}
			else
				if(disa[v]==disa[tempops]+line[i].w)
					(totb[v]+=totb[tempops])%=mod;
		}
	}
}


int main()
{
	ios::sync_with_stdio(false);
	cin>>n>>m;
	int one,two;
	cin>>one>>two;
	for(int i=1;i<=m;i++)
	{
		int u,v,d;
		cin>>u>>v>>d;
		addline(u,v,d);
		addline(v,u,d);
	}
	for(int i=1;i<=n;i++)
	{
		dis1[i]=dis2[i]=1e18;
	}
	dij(one,dis1,tot1);
	q={};
	memset(vis,0,sizeof(vis));
	dij(two,dis2,tot2);
	long long tempans=tot1[two]*tot2[one]%mod;
	for(int i=1;i<=n;i++)
	{
		if(dis1[i]==dis2[i])
		{
			if(dis1[i]+dis2[i]==dis2[one] && dis1[i]+dis2[i]==dis1[two])
				tempans=tempans-tot1[i]*tot2[i]%mod*tot1[i]%mod*tot2[i]%mod,tempans%=mod;
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=head[i];j;j=line[j].pre)
		{
			int v=line[j].to;
			if(dis1[i]+dis2[v]+line[j].w==dis1[two] && dis1[i]+line[j].w>dis2[v] && dis2[v]+line[j].w>dis1[i])
				tempans=tempans-tot1[i]*tot2[v]%mod*tot1[i]%mod*tot2[v]%mod,tempans%=mod;
		}
	}
	cout<<(tempans%mod+mod)%mod;
	return 0;
}

可是我之前每一步不都把tempans取模了吗?

2023/7/6 16:45
加载中...