您的位置:首页 > 其它

[SPFA的SLF优化] Codeforces Round #257 (Div. 1) B

2014-07-21 10:06 218 查看
B. Jzzhu and Cities

题目链接 : http://codeforces.com/contest/449/problem/B
题目大意 : n个城市由公路连接,现有一些从首都到各个城市的铁路,询问哪些铁路可以被删掉,铁路可以被删掉当且仅当最短路径不改变时

思路 :建图做一遍最短路,考虑在最短路图上:

1° 如果有一个点存在公路到达,那么到这个点的公路都可以被删掉

2° 如果某点在最短路图上全是铁路连接,那么这些铁路中至少保留一条

另外这题果的SPFA过不了,要加上SLF优化(见下面)

Code :

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <deque>
using namespace std;
#define foru(i, a, b) for (int i=(a); i<=(b); i++)
#define ford(i, a, b) for (int i=(a); i>=(b); i--)
#define clr(a) memset(a, 0, sizeof(a));
#define N 100010
#define M 1000010
typedef long long ll;
const ll INF = 100000000ll * 100000000ll;

int n, m, t, tot;
int adj
, next[M], aim[M], num
;
ll len[M];
bool rou[M];

void add(int a, int b, ll c){
tot ++;
len[tot] = c;
aim[tot] = b;
next[tot] = adj[a];
adj[a] = tot;
}

void init(){
clr(num); clr(rou);
scanf("%d%d%d", &n, &m, &t);
foru(i, 1, m){
int u, v; ll c;
scanf("%d%d%I64d", &u, &v, &c);
add(u, v, c);
add(v, u, c);
}
foru(i, 1, t){
int x; ll c;
scanf("%d%I64d", &x, &c);
num[x] ++;
add(1, x, c); rou[tot] = 1;
add(x, 1, c); rou[tot] = 1;
}
}

deque<int> s;
ll dis
;
bool v
;
bool sta
;

void spfa(){
clr(v); v[1] = 1; s.push_back(1);
foru(i, 2, n) dis[i] = INF; dis[1] = 0ll;
while (! s.empty()){
int x = s.front();
s.pop_front(); v[x] = 0;
int k = adj[x];
while (k){
int tx = aim[k];
if (dis[x] + len[k] == dis[tx]){
if (! rou[k]) sta[tx] = 1;
}
if (dis[x] + len[k] < dis[tx]){
dis[tx] = dis[x] + len[k];
if (! v[tx]){
v[tx] = 1;
if (! s.empty()) {
if (dis[tx] > dis[s.front()]) s.push_back(tx);
else s.push_front(tx);
} else s.push_back(tx);
}
if (! rou[k]) sta[tx] = 1;
else sta[tx] = 0;
}
k = next[k];
}
}
}

void work(){
int ans = 0;
foru(i, 1, n)
if (sta[i]) ans += num[i];
else if (num[i] > 0) ans += (num[i]-1);
printf("%d\n", ans);
}

int main(){
//  freopen("B.txt", "r", stdin);
init();
spfa();
work();
return 0;
}


Tips:

SPFA的SLF优化:在入队操作时,对于入队的点j比较对首点i,若Dj <= Di 将j点插入对首,否者将j点插入队尾

void spfa(){
clr(v); v[1] = 1; s.push_back(1);
foru(i, 2, n) dis[i] = INF; dis[1] = 0ll;
while (! s.empty()){
int x = s.front();
s.pop_front(); v[x] = 0;
int k = adj[x];
while (k){
int tx = aim[k];
if (dis[x] + len[k] < dis[tx]){
dis[tx] = dis[x] + len[k];
if (! v[tx]){
v[tx] = 1;
if (! s.empty()) {
if (dis[tx] > dis[s.front()]) s.push_back(tx);
else s.push_front(tx);
} else s.push_back(tx);
}
}
k = next[k];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: