题意:给出 n 个细菌,m 种仪器,细菌有 k 种,每种细菌数量 c[i],给出从第 ui 细菌到第 vi 个细菌转化需要的花费。判断同种细菌之间的转化是不是花费都可以是0,如果可以再输出不同种细菌之间转化的最小花费。
析:首先要判断是同种细菌是不是转化花费为0,如果数据小的话,可以用Floyd,但是数据太大,我们可以考虑用并查集,如果在两种细菌之间转化花费为0,那么我们就用并查集将它们连接起来,然后再检查同种细菌之间转化是不是可以为0,直接用并查集判断是不是在同一集合就好,最后再求不同细菌之间转化的最小花费,因为要想不同细菌之间转化最少,那么必然是第 i 种细菌中的第 u 个细菌和第 j 种细菌中第 v 个细菌直接相连,由于数据较小,可以用Floyd,来求解。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e16; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e5 + 10; const int mod = 1000000007; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int p[maxn]; int Find(int x){ return x == p[x] ? x : p[x] = Find(p[x]); } int c[maxn]; int dp[510][510]; int main(){ int K; scanf("%d %d %d", &n, &m, &K); for(int i = 1; i <= n; ++i) p[i] = i; memset(dp, INF, sizeof dp); for(int i = 1; i <= K; ++i){ scanf("%d", c+i); c[i] += c[i-1]; dp[i][i] = 0; } for(int i = 0; i < m; ++i){ int u, v, val; scanf("%d %d %d", &u, &v, &val); if(val == 0){ int x = Find(u); int y = Find(v); if(x != y) p[y] = x; } int pos1 = lower_bound(c+1, c+1+K, u) - c; int pos2 = lower_bound(c+1, c+1+K, v) - c; dp[pos1][pos2] = dp[pos2][pos1] = min(dp[pos1][pos2], val); } bool ok = true; int cnt = 1; int x = Find(1); for(int i = 2; i <= n && ok; ++i){ if(i <= c[cnt]){ int y = Find(i); if(x != y) ok = false; } else{ x = Find(c[++cnt]); int y = Find(i); if(x != y) ok = false; } } if(!ok){ puts("No"); return 0; } for(int k = 1; k <= K; ++k) for(int i = 1; i <= K; ++i) for(int j = 1; j <= K; ++j) if(dp[i][k] != INF && dp[k][j] != INF) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]); puts("Yes"); for(int i = 1; i <= K; ++i) for(int j = 1; j <= K; ++j) if(j == K) printf("%d\n", dp[i][j] == INF ? -1 : dp[i][j]); else printf("%d ", dp[i][j] == INF ? -1 : dp[i][j]); return 0; }