题目链接
最小树形图的学习链接
这道题就是得处理哪个点是我们认为的出发点,就是以哪个点为起点开始进去,那么我们总不能一一去遍历吧,那样子的时间复杂度就是O(N*N*E),所以,我们得想个处理的办法,就是用一个绝对恰好大的边增添到每个边上去,用一个万能节点‘0’出发,而它最早到达的(即是最早使用的边)减去对应的M再-1,就是对应的之前的节点序号。
剩下的就是,最小树形图的模板了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 1005;
const ll INF = 0x3f3f3f3f;
int N, M, pos;
struct Eddge
{
int u, v;
ll val;
Eddge(int a=0, int b=0, ll c=0):u(a), v(b), val(c) {}
}edge[maxN*maxN];
int pre[maxN], vis[maxN], id[maxN];
ll in[maxN];
ll Dir_MST(int root, int V, int E)
{
ll ans = 0;
while(true)
{
for(int i=0; i<V; i++) in[i] = INF;
for(int i=1; i<=E; i++)
{
int u = edge[i].u, v = edge[i].v;
if(u != v && in[v] > edge[i].val)
{
in[v] = edge[i].val;
pre[v] = u;
if(u == root) pos = i;
}
}
for(int i=0; i<V; i++)
{
if(i == root) continue;
if(in[i] == INF) return -1;
}
int cnt = 0;
memset(vis, -1, sizeof(vis)); memset(id, -1, sizeof(id));
in[root] = 0;
for(int i=0; i<V; i++)
{
ans += in[i];
int v = i;
while(vis[v] != i && id[v] == -1 && v != root)
{
vis[v] = i;
v = pre[v];
}
if(v != root && id[v] == -1)
{
for(int u=pre[v]; u!=v; u=pre[u]) id[u] = cnt;
id[v] = cnt++;
}
}
if(cnt == 0) return ans;
for(int i=0; i<V; i++) if(id[i] == -1) id[i] = cnt++;
for(int i=1; i<=E; i++)
{
int u = edge[i].u, v = edge[i].v;
edge[i].u = id[u]; edge[i].v = id[v];
if(id[u] != id[v]) edge[i].val -= in[v];
}
V = cnt;
root = id[root];
}
return ans;
}
int main()
{
while(scanf("%d%d", &N, &M)!=EOF)
{
ll sum = 0;
for(int i=1; i<=M; i++)
{
scanf("%d%d%lld", &edge[i].u, &edge[i].v, &edge[i].val);
edge[i].u++; edge[i].v++;
sum += edge[i].val;
}
sum++;
for(int i=M+1; i<=M+N; i++) edge[i] = Eddge(0, i-M, sum);
ll ans = Dir_MST(0, N+1, N+M);
if(ans < 0 || ans - sum >= sum) printf("impossible\n");
else printf("%lld %d\n", ans - sum, pos - M - 1);
printf("\n");
}
return 0;
}