奶牛回家
Question:AcWing 1375.奶牛回家
Question Link:acwing.com/problem/content/1377
Algorithm:Floyd
字母均按ASCII码值处理(lan )
Code:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N=128;
vector<char> v;
int g[N][N];
int p;
pair<char,int> ans;
int main()
{
ans.second=0x3f3f3f3f;
memset(g,0x3f,sizeof g);
cin >> p;
for (int i = 0; i < p; i++)
{
char a,b;
int c;
cin >> a >> b >> c;
g[(int)a][(int)b]=min(g[(int)a][(int)b],c);
g[(int)b][(int)a]=min(g[(int)a][(int)b],c);
if(a>='A'&&a<'Z') v.push_back(a);
if(b>='A'&&b<'Z') v.push_back(b);
}
for (int k = 1; k <= N; k++)
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
g[i][j] = min(g[i][j],g[i][k] + g[k][j]);
vector<char>::iterator it=v.begin();
for(;it!=v.end();it++)
{
if(ans.second>g[(int)*it]['Z'])
{
ans.second=g[(int)*it]['Z'];
ans.first=*it;
}
}
cout << ans.first << ' ' << ans.second << endl;
}
Algorithm:dijkstra
啊哈哈哈哈,dijkstra算法来喽! 照样还是用 ASCII (Lazy )
Code:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=128;
int g[N][N];
int dist[N];
int p;
bool st[N];
void dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist['Z']=0;
for (int i = 65; i <= 122; i++)
{
int t=-1;
for (int j = 65; j <= 122; j++)
{
if(!st[j]&&(t==-1||dist[t]>dist[j])) t=j;
}
st[t]=true;
for (int j = 65; j <= 122; j++)
{
dist[j]=min(dist[j],dist[t]+g[t][j]);
}
}
}
int main()
{
memset(g,0x3f,sizeof g);
for (int i = 0; i < N; i++) g[i][i]=0;
cin >> p;
for (int i = 0; i < p; i++)
{
char a,b;
int c;
cin >> a >> b >> c;
g[(int)a][(int)b]=min(g[(int)a][(int)b],c);
g[(int)b][(int)a]=min(g[(int)a][(int)b],c);
}
dijkstra();
int ans=0x3f3f3f3f,anshome;
for (int i = 'A'; i < 'Z'; i++)
{
if(ans>dist[i])
{
ans=dist[i];
anshome=i;
}
}
cout << char(anshome) << ' ' << ans << endl;
return 0;
}
如有疑问欢迎在评论区留言或者通过Email联系我
My Email:Wizzy-Ang@qq.com 欢迎大家关注我的个人公众号WizzyAngShare,(还有个人博客)
我会在这里分享编程语言语法,算法,及区块链的相关知识,还有各种奇奇怪怪的小知识等着你~
虽然现在这个公众号有亿点草率 ,我会努力更新的~~~
|