hdu 3371 Connect the Cities(最小生成树)
2013-04-16 18:16
393 查看
/* hdu 神坑啊! c++能过g++TLE!!!尼玛
*/
#include<cstdio>
#include<cstring>
#define INF 1<<30
int map[510][510],low[510],vis[510];
int n,m,k;
int init()
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
map[i][j] = INF;
memset(vis,0,sizeof(vis));
return 0;
}
int prim()
{
int ans=0;
for(int i = 0; i <= n; i++)
low[i] = map[1][i];
vis[1] = 1;
for(int i = 1; i < n; i++)
{
int temp = INF,pos=-1;
for(int j = 1; j <= n; j++)
if(!vis[j]&&temp>low[j])
{
temp=low[j];
pos = j;
}
if(pos==-1) return -1;
vis[pos] = 1;
ans += low[pos];
for(int j = 1; j <= n; j++)
if(!vis[j]&&low[j]>map[pos][j])
low[j] = map[pos][j];
}
return ans;
}
int main()
{
int t,a,b,c;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d",&n,&m,&k);
init();
for(int i = 0; i < m; i++)
{
scanf("%d%d%d",&a,&b,&c);
if(c<map[a][b])
map[a][b] = map[b][a] = c;
}
int tm[510];
while(k--)
{
scanf("%d",&a);
for(int i = 0; i < a; i++)
{
scanf("%d",&tm[i]);
}
for(int i = 0; i < a; i++)
for(int j = 0; j < a; j++)
if(i!=j)
map[tm[i]][tm[j]] = 0;
}
printf("%d\n",prim());
}
return 0;
}
*/
#include<cstdio>
#include<cstring>
#define INF 1<<30
int map[510][510],low[510],vis[510];
int n,m,k;
int init()
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
map[i][j] = INF;
memset(vis,0,sizeof(vis));
return 0;
}
int prim()
{
int ans=0;
for(int i = 0; i <= n; i++)
low[i] = map[1][i];
vis[1] = 1;
for(int i = 1; i < n; i++)
{
int temp = INF,pos=-1;
for(int j = 1; j <= n; j++)
if(!vis[j]&&temp>low[j])
{
temp=low[j];
pos = j;
}
if(pos==-1) return -1;
vis[pos] = 1;
ans += low[pos];
for(int j = 1; j <= n; j++)
if(!vis[j]&&low[j]>map[pos][j])
low[j] = map[pos][j];
}
return ans;
}
int main()
{
int t,a,b,c;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d",&n,&m,&k);
init();
for(int i = 0; i < m; i++)
{
scanf("%d%d%d",&a,&b,&c);
if(c<map[a][b])
map[a][b] = map[b][a] = c;
}
int tm[510];
while(k--)
{
scanf("%d",&a);
for(int i = 0; i < a; i++)
{
scanf("%d",&tm[i]);
}
for(int i = 0; i < a; i++)
for(int j = 0; j < a; j++)
if(i!=j)
map[tm[i]][tm[j]] = 0;
}
printf("%d\n",prim());
}
return 0;
}
相关文章推荐
- HDU-3371 Connect the Cities(最小生成树)
- HDU_3371 Connect the cities(最小生成树)
- hdu 3371 Connect the Cities(最小生成树))
- hdu 3371 Connect the Cities (最小生成树)
- HDU 3371 Connect the Cities 【最小生成树,Prime算法+Kruskal算法】
- HDU 3371 Connect the Cities 最小生成树(和关于sort和qsort的一些小发现)
- hdu 3371 Connect the Cities(最小生成树kruskal)
- hdu 3371 Connect the Cities 最小生成树
- HDU 3371 Connect the Cities (最小生成树 并查集+克鲁斯卡尔)
- hdu 3371 最小生成树Connect the Cities
- hdu 3371(Connect the Cities)(最小生成树)
- HDU 3371 Connect the Cities 【最小生成树】
- HDU 3371 Connect the Cities(最小生成树)
- 文章标题 HDU 3371 : Connect the Cities(最小生成树--Kruskal+并查集)
- hdu 3371 Connect the Cities (最小生成树Prim)
- HDU 3371 Connect the Cities 并查集+Kruskal算法+最小生成树
- HDU 3371 Connect the Cities 最小生成树
- (step6.1.7)hdu 3371(Connect the Cities——最小生成树)
- HDU 3371 Connect the Cities (最小生成树+克鲁斯卡尔算法)
- [HDU] 3371 Connect the Cities [最小生成树,并查集,Kruskal]