关于图论实在是太薄弱了,有时间加强这方面的练习,虽然对于其他知识也是很薄弱。
还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 41332 Accepted Submission(s): 18859
Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度。
Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output
3
5
Hint
Hint
Huge input, scanf is recommended.
偷偷刷几个水题,大神不会叼我吧233.
prim模板题,不能再模板了。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
#include<string>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#include<set>
#include<map>
#include<cstdio>
#include<limits.h>
#define MOD 1000000007
#define fir first
#define sec second
#define fin freopen("/home/ostreambaba/文档/input.txt", "r", stdin)
#define fout freopen("/home/ostreambaba/文档/output.txt", "w", stdout)
#define mes(x, m) memset(x, m, sizeof(x))
#define Pii pair<int, int>
#define Pll pair<ll, ll>
#define INF 1e9+7
#define Pi 4.0*atan(1.0)
#define lowbit(x) (x&(-x))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-12;
const int maxn = 101;
using namespace std;
inline int read(){
int x(0),f(1);
char ch=getchar();
while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*f;
}
struct Edge{
int v,w;
friend bool operator<(const Edge &a,const Edge &b){
return a.w>b.w;
}
};
int mp[maxn][maxn],vis[maxn],dis[maxn],n,q;
void Prim()
{
priority_queue<Edge> edge;
fill(dis+1,dis+n+1,INF);
mes(vis,0);
Edge cur;
int ans=0;
cur.v=1,cur.w=0;
edge.push(cur);
while(!edge.empty()){
cur=edge.top();
edge.pop();
if(vis[cur.v]){
continue;
}
vis[cur.v]=1;
ans+=cur.w;
for(int i=1;i<=n;++i){
if(!vis[i]&&mp[cur.v][i]<dis[i]){
Edge next;
next.v=i;
next.w=dis[i]=mp[cur.v][i];
edge.push(next);
}
}
}
printf("%d\n",ans);
}
int main()
{
int a,b,c;
while(~scanf("%d",&n)&&n){
mes(mp,0);
int m=n*(n-1)/2;
while(m--){
a=read(),b=read(),c=read();
mp[a][b]=mp[b][a]=c;
}
Prim();
}
return 0;
}