最开始想法超时,考虑是否有重复计算,先算出存起来。
STL:
q.top() 访问队头元素
lower_bound() 对一个升序的容器返回“插入元素”应该在的“地址“”,若对降序容器,则需在第四个参数加 greater<int> ()
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
struct Node{
int length,v;
Node(int length ,int v){
this -> length = length;
this -> v = v;
}
bool operator < ( const Node& b) const{
return length > b.length;
}
};
int main()
{
int n,m,s,t,a,b;
int T[1010],dist1[1010],dist2[1010];
vector<int> path[1010];
priority_queue<Node> q;
while(~scanf("%d%d%d%d",&n,&m,&s,&t)){
memset(T,0,sizeof(T));
for(int i = 1 ; i <= n; i++){
path[i].clear();
}
while(!q.empty()){
q.pop();
}
for(int i =1; i <= m ; i++){
scanf("%d%d",&a,&b);
path[a].push_back(b);
path[b].push_back(a);
}
Node node(0,s);
q.push(node);
while(!q.empty()){
node = q.top(); q.pop();
if(T[node.v]) continue;
T[node.v] = 1;
dist1[node.v] = node.length;
for(int i = 0; i < path[node.v].size(); i++){
int tmp1 = path[node.v][i];
if(T[tmp1]) continue;
Node tmp2(node.length + 1,tmp1);
q.push(tmp2);
}
}
memset(T,0,sizeof(T));
while(!q.empty()){
q.pop();
}
Node node2(0,t);
q.push(node2);
while(!q.empty()){
node2= q.top(); q.pop();
if(T[node2.v]) continue;
T[node2.v] = 1;
dist2[node2.v] = node2.length;
for(int i = 0; i < path[node2.v].size(); i++){
int tmp1 = path[node2.v][i];
if(T[tmp1]) continue;
Node tmp2(node2.length + 1,tmp1);
q.push(tmp2);
}
}
int cnt = 0;
for(int i = 1; i < n; i++){
sort(path[i].begin(),path[i].end());
for(int j = i+1; j <= n ; j++){
int k = lower_bound(path[i].begin(),path[i].end(),j) - path[i].begin();
if(k != path[i].size() && path[i][k] == j) continue;
if( (dist1[i] + dist2[j] + 1 >= dist1[t]) && (dist1[j] + dist2[i] + 1 >= dist1[t]) )
cnt ++;
}
}
printf("%d\n",cnt);
}
return 0;
}