题意:求强联通分量之间的距离
解法:先进行强联通缩点 然后读入询问 对于每一个询问 都跑一次Dijstra
然后得出答案 要注意的是,这里使用floyed 会超时(也许是我写的太差)
所以要用另外两种最短路算法
#pragma comment(linker,"/STACK:102400000,102400000")
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long ll; //记得必要的时候改成无符号
const int maxn=100005; //点数
const int maxm=500005; //边数
const int INF=1000000000;
int mp[511][511];
int scan()
{
int res=0,ch;
while(!((ch= getchar())>='0'&&ch<='9')){
if(ch==EOF)return 1<<30;
}
res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')
res=res*10+(ch-'0');
return res;
}
struct EdgeNode
{
int from;
int to;
int next,value;
}edge[maxm];
int head[maxn],cnt;
void add(int x,int y,int z)
{
edge[cnt].from=x;edge[cnt].to=y;
edge[cnt].value=z;
edge[cnt].next=head[x];head[x]=cnt++;
}
void init()
{
cnt=1;
memset(head,-1,sizeof(head));
}
int dfn[maxn],low[maxn],ins[maxn];
int cixu,scc_count,n,ru[maxn],chu[maxn],sd[maxn];
stack<int>S;
void dfs(int u)
{
int v,x;
dfn[u]=low[u]=++cixu;
S.push(u);
ins[u]=1;
for(int i=head[u];i!=-1;i=edge[i].next)
{
v=edge[i].to;
if(!dfn[v]){
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(ins[v])
//如果已经搜过,并且在栈里面,如果不在栈里面,说明该点属于其他的强连通分量里面
low[u]=min(low[u],dfn[v]);
//此处low代替dfn也是可以的,但是在tarjan求无向图的时候不能
}
if(dfn[u]==low[u])
//表示u为此强连通分量第一个被发现的点,属于该强连通分量的所有的其他点都在栈中,他的上面
{
scc_count++;
do
{
x=S.top();
S.pop();
sd[x]=scc_count;
ins[x]=0;
}while(x!=u);
}
}
void tarjan()
{
for(int i=1;i<=n;i++)sd[i]=i; //缩点标记数组
memset(ins,0,sizeof(ins));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
cixu=scc_count=0;
for(int i=1;i<=n;i++) //可能所给的图为不连通的图,分块,因此需要遍历所有的点
{
if(!dfn[i])
dfs(i);
}
}
void SD()
{
int x,y,len=cnt;
init();
memset(ru,0,sizeof(ru));
memset(chu,0,sizeof(chu));
for(int i=1;i<len;i++){
x=sd[edge[i].from]; y=sd[edge[i].to];
if(x==y)continue;
mp[x][y]=min(mp[x][y],edge[i].value);
}
}
// scc_count 1...
int dis[maxn],vis[maxn];
void dij(int t)
{
for(int i=1;i<=scc_count;++i)dis[i]=mp[t][i],vis[i]=0;
vis[t]=1,dis[t]=0;
int mi,pos=1;
for(int i=0;i<scc_count;++i)
{
mi=INF;
for(int j=1;j<=scc_count;++j)
{
if(!vis[j]&&mi>dis[j])
{
mi=dis[j];
pos=j;
}
}
if(mi==INF)break;
vis[pos]=1;
for(int j=1;j<=scc_count;++j)
{
if(!vis[j]&&dis[j]>dis[pos]+mp[pos][j]){
dis[j]=dis[pos]+mp[pos][j];
}
}
}
}
int main()
{
int m,i,p,sum,x,y,z;
while(~scanf("%d%d",&n,&m)){
if(n==0&&m==0)break;
init(); sum=0; p=0;
for(i=1;i<=m;i++){
x=scan();y=scan();z=scan();
add(x,y,z);
}
int _;scanf("%d",&_);
tarjan();
for(int i=1;i<=scc_count;++i)
for(int j=1;j<=scc_count;++j)
mp[i][j]=(i==j)?0:INF;
SD();
int a,b;
while(_--){
scanf("%d%d",&a,&b);
a=sd[a];b=sd[b];
dij(a);
if(dis[b]==INF)printf("Nao e possivel entregar a carta\n");
else printf("%d\n",dis[b]);
}
printf("\n");
}
return 0;
}