UVA - 10462

题意: 求次小生成树的模板题,这道题因为有重边的存在,所以用kruskal求比较好。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <list>
#include <cstdlib>
#include <iterator>
#include <cmath>
#include <iomanip>
#include <bitset>
#include <cctype>
using namespace std;
//#pragma comment(linker, "/STACK:102400000,102400000") //c++
#define lson (l , mid , rt << 1)
#define rson (mid + 1 , r , rt << 1 | 1)
#define debug(x) cerr << #x << " = " << x << "\n";
#define pb push_back
#define pq priority_queue typedef long long ll;
typedef unsigned long long ull; typedef pair<ll ,ll > pll;
typedef pair<int ,int > pii; //priority_queue<int> q;//这是一个大根堆q
//priority_queue<int,vector<int>,greater<int> >q;//这是一个小根堆q
#define fi first
#define se second
#define endl '\n' #define OKC ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define FT(A,B,C) for(int A=B;A <= C;++A) //用来压行
#define REP(i , j , k) for(int i = j ; i < k ; ++i)
//priority_queue<int ,vector<int>, greater<int> >que; const ll mos = 0x7FFFFFFF; //
const ll nmos = 0x80000000; //-2147483648
const int inf = 0x3f3f3f3f; template<typename T>
inline T read(T&x){
x=;int f=;char ch=getchar();
while (ch<''||ch>'') f|=(ch=='-'),ch=getchar();
while (ch>=''&&ch<='') x=x*+ch-'',ch=getchar();
return x=f?-x:x;
}
// #define _DEBUG; //*//
#ifdef _DEBUG
freopen("input", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
/*-----------------show time----------------*/
const int maxn = ;
int n,m;
struct node
{
int u,v;
int c;
bool vis;
}e[maxn]; bool cmp(node a,node b){
return a.c < b.c;
}
int fa[];
int sum,sec_tree;
vector<int>g[];
int len[][];
int find(int x){
if(fa[x]==x)return x;
else return fa[x] = find(fa[x]);
}
void kruskal(){ for(int i=; i<=n; i++){
fa[i] = i;
g[i].clear();
g[i].pb(i);
} sort(e+,e++m,cmp);
sum = ;
int k=;
for(int i=; i<=m; i++){
if(k==n-)break; int fx = find(e[i].u);
int fy = find(e[i].v); if(fx!=fy){
sum += e[i].c; k++;
e[i].vis = true; int len1 = g[fx].size();
int len2 = g[fy].size(); for(int j=; j<len1; j++){
for(int t=; t<len2; t++){
len[g[fx][j]][g[fy][t]] = len[g[fy][t]][g[fx][j]] = e[i].c;
}
} fa[fy] = fx; int tmp[]; for(int j=; j<len1; j++){
tmp[j] = g[fx][j];
}
for(int j=; j<len2; j++){
g[fx].pb(g[fy][j]);
}
for(int j=; j<len1; j++){
g[fy].pb(tmp[j]);
}
}
} sec_tree = inf;
for(int i=; i<=m; i++){
if(e[i].vis==false){
sec_tree = min(sec_tree, sum - len[e[i].u][e[i].v] + e[i].c);
} }
// debug(sec_tree);
}
int main(){
int t_t;
scanf("%d", &t_t);
for(int T = ; T <= t_t;T++){
printf("Case #%d : ", T);
memset(len,,sizeof(len));
scanf("%d%d", &n, &m);
for(int i=; i<=m; i++){
scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].c);
e[i].vis = false;
}
kruskal();
int flag =;
for(int i=; i<=n; i++){
if(find(i) != find()){
puts("No way");
flag = ;
break;
}
}
if(flag == ) continue;
if(sec_tree<inf){
printf("%d\n",sec_tree);
}
else printf("No second way\n");
}
return ;
}

UVA - 10462

05-17 19:25