coder • 1年前
// // Created by Administrator on 2023/8/8. //
using namespace std; const int MAX_VERTICES = 100; // 最大顶点数量 struct Graph {
int numVertices; // 图的顶点数量
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES]; // 邻接矩阵
// 构造函数
Graph(int n) {
numVertices = n;
// 初始化邻接矩阵为无穷大
for (int i = 1; i <= numVertices; i++) {
for (int j = 1; j <= numVertices; j++) {
adjacencyMatrix[i][j] = INT_MAX;
}
}
}
};
struct Graph1 {
int numVertices; // 图的顶点数量
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES]; // 邻接矩阵
// 构造函数
Graph1(int n) {
numVertices = n;
// 初始化邻接矩阵为无穷大
for (int i = 1; i <= numVertices; i++) {
for (int j = 1; j <= numVertices; j++) {
adjacencyMatrix[i][j] = 0;
}
}
}
};
typedef struct EdgeS{
int F;
int T;
int W;
}; bool cmp(struct EdgeS a , struct EdgeS b){
return a.W<b.W;
} bool visited[MAX_VERTICES] = {false}; bool cmp1(struct EdgeS a , struct EdgeS b){
return a.W>b.W;
} // 添加边 void addEdge(Graph &G , int numOfEdge, EdgeS *E1) {
int a , b ,w;
for (int i = 1; i <= numOfEdge ; ++i) {
cin>>a>>b>>w;
G.adjacencyMatrix[a][b] = 1;
G.adjacencyMatrix[b][a] = 1; // 如果是有向图则省略这行
E1[i].F = a;
E1[i].T = b;
E1[i].W = w;
}
}
bool dfs(Graph1 G,int s,int t,int m,bool visited[MAX_VERTICES]){
visited[s] = true;
for (int i = 1; i <= m; ++i) {
if (G.adjacencyMatrix[s][i] == 1 && !visited[i]) {
if (i == t){
return true;
}
if(dfs(G,i,t,m, visited)){
return true;
}
}
}
return false;
}
void kruskal(Graph &G,Graph1 &G1,EdgeS *E1,int m, int s,int t){
EdgeS E2[m-1];
set<int> set1;
set<int> set2;
int j = 0;
for (int i = 1; i <= m; ++i) {
int x = E1[i].F;
int y = E1[i].T;
if (set1.find(E1[i].F)==set1.end()||set1.find(E1[i].T)==set1.end()){
E2[j].F = E1[i].F;
E2[j].T = E1[i].T;
E2[j++].W = E1[i].W;
G1.adjacencyMatrix[x][y] = 1;
G1.adjacencyMatrix[y][x] = 1;
}
int t1 = 0;
if (set2.size()==2){
t1 = 1;
}
if (x == s||x == t||t1){
if (!t1){
set2.insert(y);
}
if (set2.size()==2){
if (dfs(G1,s,t,m,visited)){
sort(E2,E2+j, cmp1);
cout<<E2[0].W;
return;
}
}
for (int k = 1; k <= m; ++k) {
visited[k] = false;
}
}
if (y == t||y == s||t1){
if (!t1){
set2.insert(y);
}
if (set2.size()==2){
if (dfs(G1,s,t,m,visited)){
sort(E2,E2+j, cmp1);
cout<<E2[0].W;
return;
}
}
for (int k = 1; k <= m; ++k) {
visited[k] = false;
}
}
}
}
int main() { // cout<<"请输入图的顶点数和边数:";
int n , m,s,t;
cin>>n>>m>>s>>t;
EdgeS E1[m];
Graph g(n);
Graph1 g1(n);
// 添加边
addEdge(g, m, E1);
sort(E1+1,E1+m+1, cmp);
kruskal(g,g1,E1,m,s,t);
return 0;
}
评论:
请先登录,才能进行评论