HDU 2121 Ice_cream’s world II(不定根最小树形图)
题目:
Ice_cream’s world II
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1610 Accepted Submission(s): 354
Problem Description
After awarded lands to ACMers, the queen want to choose a city be her capital. This is an important event in ice_cream world, and it also a very difficult problem, because the world have N cities and M roads, every road was directed. Wiskey is a chief engineer in ice_cream world. The queen asked Wiskey must find a suitable location to establish the capital, beautify the roads which let capital can visit each city and the project’s cost as less as better. If Wiskey can’t fulfill the queen’s require, he will be punishing.
Input www.zzzyk.com
Every case have two integers N and M (N<=1000, M<=10000), the cities numbered 0…N-1, following M lines, each line contain three integers S, T and C, meaning from S to T have a road will cost C.
Output
If no location satisfy the queen’s require, you must be output “impossible”, otherwise, print the minimum cost in this project and suitable city’s number. May be exist many suitable cities, choose the minimum number city. After every case print one blank.
Sample Input
3 1
0 1 1
4 4
0 1 10
0 2 10
1 3 20
2 3 30
Sample Output
impossible
40 0
Author
Wiskey
Source
HDU 2007-10 Programming Contest_WarmUp
Recommend
威士忌
分析与总结:
不定根最小树形图问题,解决方法是设计一个“虚拟新根点”,这个从这个结点出发可以到达所有点,并且权值是一个很大的值(比所有权值之和大),然后找这个跟结点是否有最小树形图。
而求出真正的跟结点的方法很巧妙, 利用边的位置与虚拟结点的关系。
代码:
[cpp]
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
const int VN = 1005;
const int INF = 0x7fffffff;
int ans_root;
template<typename Type>
class Directed_MST{
public:
void init(int _n){
n=_n+1; size=0; ans=0;
}
void insert(int u, int v, Type _w){
E[size++].set(u,v,_w);
}
Type directed_mst(int root){
while(true){
// 1.找最小的前驱边
for(int i=1; i<n; ++i)
in[i]=INF;
for(int i=0; i<size; ++i){
int u=E[i].u, v=E[i].v;
if(E[i].w < in[v] && u!=v){
pre[v] = u;
in[v] = E[i].w;
if(u==root){
ans_root = i; // 保存的是边的位置i,而不是v
}
}
}
for(int i=1; i<n; ++i)if(i!=root){
if(in[i]==INF) return -1;
}
// 2.找环
int MXid = 1;
in[root] = 0;
memset(id, -1, sizeof(id));
memset(vis, -1, sizeof(id));
for(int i=1; i<n; ++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] = MXid;
}
id[v] = MXid++;
}
}
if(MXid==1) break; //无环
for(int i=1; i<n; ++i)
if(id[i]==-1) id[i] = MXid++;
// 3.缩点,重新标记
for(int i=0; i<size; ++i){
int u=E[i].u, v=E[i].v;
E[i].u
补充:软件开发 , C++ ,