P2505 [HAOI2012] 道路

2018-04-02 20:10:27

（在最短路图上如果存在u->v,则cnt2[u]+=cnt2[v]）

ps:不要忘记模数，以及循环时判断当前边是否在最短路图上

#include<cstdio>
#include<cstring>
#include<cctype>
#include<deque>
#include<queue>
#include<algorithm>
#define reg register
using namespace std;
const int N=1505,mod=1e9+7;
struct edge
{
int from,to,nxt,dis;
}edge[5005];
bool exist[N],vis[5005];
{
int x=0,w=1;
char c=getchar();
while (!isdigit(c)&&c!='-') c=getchar();
if (c=='-') c=getchar(),w=-1;
while (isdigit(c))
{
x=(x<<1)+(x<<3)+c-'0';
c=getchar();
}
return x*w;
}
inline void add_edge(int from,int to,int dis)
{
edge[num].to=to;
edge[num].from=from;
edge[num].dis=dis;
}
inline void spfa(int s)
{
deque<int>q;
memset(dis,127/3,sizeof(dis));
memset(exist,0,sizeof(exist));
memset(vis,0,sizeof(vis));
q.push_back(s); exist[s]=1; dis[s]=0;
while (!q.empty())
{
int u=q.front();
q.pop_front(); exist[u]=0;
{
int v=edge[i].to,d=edge[i].dis;
if (dis[v]>dis[u]+d)
{
dis[v]=dis[u]+d;
if (!exist[v])
{
if (!q.empty()&&dis[v]<dis[q.front()]) q.push_front(v);
else q.push_back(v); exist[v]=1;
}
}
}
}
for (reg int i=1;i<=m;i++)
{
int u=edge[i].from,v=edge[i].to;
vis[i]=(dis[u]+edge[i].dis==dis[v]);
}
}
inline void topsort(int k)
{
queue<int>q;
memset(in,0,sizeof(in));
memset(cnt1,0,sizeof(cnt1));
memset(cnt2,0,sizeof(cnt2));
q.push(k); cnt1[k]=1; num=0;
for (reg int i=1;i<=m;i++)
if (vis[i]) ++in[edge[i].to];
while (!q.empty())
{
int u=q.front(); q.pop(); res[++num]=u;
{
if (!vis[i]) continue;
int v=edge[i].to;
if (!--in[v]) q.push(v);
cnt1[v]=(cnt1[u]+cnt1[v])%mod;
}
}
for (reg int t=num;t;t--)
{
int u=res[t]; ++cnt2[u];
{
if (!vis[i]) continue;
int v=edge[i].to;
cnt2[u]=(cnt2[u]+cnt2[v])%mod;
}
}
}
inline void solve(int k)
{
spfa(k); topsort(k);
for (reg int i=1;i<=m;i++)
{
int u=edge[i].from,v=edge[i].to;
if (vis[i]) ans[i]=(1ll*ans[i]+cnt1[u]*cnt2[v]%mod)%mod;
}
}
int main()
{
}