链接:
2737. 找到最近的标记节点
题意:
给一个n节点有向图,求节点s和点集marked中的最短距离,没有可以的到达的点则返回-1
解:
摇了一题困难过了2/3,搞不定了
没有负权边的单源最短距离,迪杰斯特拉
跑一组WA了(忘记最大改最小了)的案例结果执行出错了,怎么肥四啊力扣
实际代码:
#include<bits/stdc++.h>
using namespace std;
const int Nmax=5E2+7;
int minimumDistance(int n, vector<vector<int>>& edges, int s, vector<int>& marked)
{
vector<vector<int>>mps(n,vector<int>(n,INT_MAX));
for(auto &edge:edges)
{
mps[edge[0]][edge[1]]=min( mps[edge[0]][edge[1]],edge[2] );
//新图 去重
}
vector<int>distence(n,INT_MAX);distence[s]=0;
vector<bool>book(n);
int now=s,min_index,min_num=INT_MAX,ans=INT_MAX;
while(true)
{
book[now]=1;min_num=INT_MAX;
//distence[now]=0;//标记选取
auto &mp=mps[now];//遍历邻接点
for(int index=0;index<n;index++)
{
if(index!=now && mp[index]!=INT_MAX)//不是当前点且有边
{
distence[index]=min(distence[index],distence[now]+mp[index]);//更新距离
}
if(book[index]==0 && distence[index]<min_num)//选取最小的未选取的点
{
min_num=distence[index];
min_index=index;
}
}
if(min_num!=INT_MAX) now=min_index;
else break;
}
for(auto m:marked)
{
//cout<<m<<" "<<distence[m]<<endl;
ans=min(ans,distence[m]);
}
return (ans==INT_MAX?-1:ans);
}
int main()
{
vector<vector<int>> edges;
vector<int> marked;
cout<<"输入n和edges.size"<<endl;
int n,s,temp;cin>>n>>s;
for(int i=1;i<=s;i++)
{
cout<<"输入edge"<<endl;
int a,b,c;cin>>a>>b>>c;
vector<int>temp{a,b,c};
edges.push_back(temp);
}
cout<<"输入s和marked,输入EOF结束"<<endl;
cin>>s;
while(cin>>temp)
{
marked.push_back(temp);
}
int ans=minimumDistance(n,edges,s,marked);
cout<<ans<<endl;
return 0;
}
限制:
2 <= n <= 500
1 <= edges.length <= 104
edges[i].length = 3
0 <= edges[i][0], edges[i][1] <= n - 1
1 <= edges[i][2] <= 106
1 <= marked.length <= n - 1
0 <= s, marked[i] <= n - 1
s != marked[i]