图论测试题(一)第一题:longest
第一題:longest
烏托邦有n個(gè)城市,某些城市之間有公路連接。任意兩個(gè)城市都可以通過公路直接或者間接到達(dá),并且任意兩個(gè)城市之間有且僅有一條路徑(What does this imply? A tree!)。
每條公路都有自己的長(zhǎng)度,這些長(zhǎng)度都是已經(jīng)測(cè)量好的。
小修想從一個(gè)城市出發(fā)開車到另一個(gè)城市,并且她希望經(jīng)過的公路總長(zhǎng)度最長(zhǎng)。請(qǐng)問她應(yīng)該選擇哪兩個(gè)城市?這個(gè)最長(zhǎng)的長(zhǎng)度是多少?
?
Input format:
第一行n(n<=1000)。
以下n-1行每行三個(gè)整數(shù)a, b, c。表示城市a和城市b之間有公路直接連接,并且公路的長(zhǎng)度是c(c<=10000)。
Output format:
僅一個(gè)數(shù),即最長(zhǎng)長(zhǎng)度。
Sample:
Longest.in
5
1 2 2
2 3 1
2 4 3
1 5 4
?
Longest.out
9
?
說明:從城市4到城市5,經(jīng)過的路徑是4-2-1-5,總長(zhǎng)度是9。
?
裸的kruskal吧= =沒什么好說的,模板題
上代碼o(〃'▽'〃)o
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int n,m; struct node{int u;int v;int value; }e[1001]; int father[1001]; bool cmp(node e1,node e2) {return e1.value>e2.value; } void read() {scanf("%d",&n);m=0;for(int i=1;i<n;i++){m++;int u,v,w;scanf("%d%d%d",&u,&v,&w);e[m].u=u;e[m].v=v;e[m].value=w;}sort(e+1,e+m+1,cmp); } int find(int x) {if(father[x]==x) return x;else return father[x]=find(father[x]); } void merge(int x,int y) {if(father[x]!=father[y]) father[father[x]]=father[y]; } void kruskal() {int sum=0;int ans=0;for(int i=1;i<=n;i++) father[i]=i;for(int i=1;i<=m;i++){if(find(e[i].u)!=find(e[i].v)){sum++;ans+=e[i].value;merge(e[i].u,e[i].v);}if(sum==n-2){printf("%d",ans);return ;}}printf("%d",-1); } int main() {read();kruskal();return 0; } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/orange-/p/4887850.html
總結(jié)
以上是生活随笔為你收集整理的图论测试题(一)第一题:longest的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring(十九):Spring AO
- 下一篇: 20165221 实验五 网络编程与安全