题目链接:http://codeforces.com/problemset/problem/507/E
题意:给出一张N个点M条边的无向图,要选出一条从1到N的最短路,有些边是需要维修的,不在最短路上的边需要拆掉,如果有多条最短路,需要选择影响度最小的那条,影响度值 = 需要维修的边数 + 需要拆掉的边数
思路:定义图上不需要维修的边数目为sum,最短路上不需要维修的边数目为num,考虑这个影响度则 = dis[n] - num + sum - num = dis[n] + sum - 2 * num,故而只需要在spfa转移时更新num即可
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <climits>
#include <functional>
#include <deque>
#include <ctime>
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int MAXN = 101000;
const int MAXM = 201000;
const int INF = 0x3f3f3f3f;
int cnt, head[MAXN];
int dis[MAXN], pre[MAXN], vis[MAXN];
struct edge
{
int from, to, nxt, w, flag;
} e[MAXM];
void init()
{
cnt = 0;
memset(head, -1, sizeof(head));
}
void addedge(int u, int v, int w, int flag)
{
e[cnt].from = u;
e[cnt].to = v;
e[cnt].nxt = head[u];
e[cnt].flag = flag;
e[cnt].w = w;
head[u] = cnt++;
}
int num[MAXN];
void spfa(int s)
{
memset(dis, INF, sizeof(dis));
memset(vis, 0, sizeof(vis));
memset(num, 0, sizeof(num));
deque <int> que;
que.push_back(s);
vis[s] = 1, dis[s] = 0, pre[s] = -1;
while (!que.empty())
{
int u = que.front();
que.pop_front();
vis[u] = 0;
for (int i = head[u]; ~i; i = e[i].nxt)
{
int v = e[i].to;
if (dis[v] > dis[u] + e[i].w || (dis[v] == dis[u] + e[i].w && num[v] < num[u] + e[i].flag))
{
dis[v] = dis[u] + e[i].w;
num[v] = num[u] + e[i].flag;
pre[v] = u;
if (!vis[v])
{
vis[v] = 1;
if (!que.empty() && dis[v] <= dis[que.front()])
que.push_front(v);
else
que.push_back(v);
}
}
}
}
}
int main()
{
int n, m;
while (~scanf("%d%d", &n, &m))
{
init();
int sum = 0;
for (int i = 0; i < m; i++)
{
int u, v, flag;
scanf("%d%d%d", &u, &v, &flag);
addedge(u, v, 1, flag);
addedge(v, u, 1, flag);
sum += flag;
}
spfa(1);
int ans = dis[n] + sum - 2 * num[n];
cout << ans << endl;
memset(vis, 0, sizeof(vis));
int u = n;
while (u != -1)
{
vis[u] = 1;
u = pre[u];
}
for (int i = 0; i < cnt; i += 2)
{
int u = e[i].from, v = e[i].to;
if ((pre[u] == v || pre[v] == u) && (!e[i].flag && vis[u] && vis[v]))
printf("%d %d 1\n", u, v);
else if (e[i].flag && (!vis[u] || !vis[v]))
printf("%d %d 0\n", u, v);
}
}
return 0;
}