您的位置:首页 > 其它

hdoj-2122 Ice_cream’s world III

2015-08-11 17:21 239 查看

Ice_cream’s world III

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1163    Accepted Submission(s): 386


[align=left]Problem Description[/align]
ice_cream’s world becomes stronger and stronger; every road is built as undirected. The queen enjoys traveling around her world; the queen’s requirement is like II problem, beautifies the roads, by which there are some ways from every
city to the capital. The project’s cost should be as less as better.
 

[align=left]Input[/align]
Every case have two integers N and M (N<=1000, M<=10000) meaning N cities and M roads, the cities numbered 0…N-1, following N lines, each line contain three integers S, T and C, meaning S connected with T have a road will cost C.
 

[align=left]Output[/align]
If Wiskey can’t satisfy the queen’s requirement, you must be output “impossible”, otherwise, print the minimum cost in this project. After every case print one blank.
 

[align=left]Sample Input[/align]

2 1
0 1 10

4 0

 

[align=left]Sample Output[/align]

10

impossible

 

[align=left]Author[/align]
Wiskey
 

[align=left]Source[/align]
//做这种题我很容易出现Time Limit Exceeded的情况 
分析如下:
1.数组开的太小
2.scanf循环容易漏掉EOF
3.for循环条件控制容易出错,陷入死循环
希望自己能够减少此方面的错误 也希望博友们能够注意到这点小细节。
# include<stdio.h>
# include<string.h>
# include<algorithm>
# define max 10000 + 100
using namespace std;
int n, m ;
int per[1020];

void g()
{
for(int t = 0; t <= n; t++)//切记从0开始赋值
per[t] = t;
}

struct node
{
int s;
int e;
int w;
}c[max];

bool cmp(node x, node y)
{
return x.w < y.w;
}
int find(int x)
{
<span style="white-space:pre">	</span>int i = x, r = x, j; 
<span style="white-space:pre">	</span>while(r != per[r])
<span style="white-space:pre">	</span> r = per[r];
<span style="white-space:pre">	</span>while(i != r)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>j = per[i];
<span style="white-space:pre">		</span>per[i] = r;
<span style="white-space:pre">		</span>i = j;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>return r; //写递归函数就不容易漏掉return 但还是听学长的建议吧 少用递归为妙。
}
//递归函数写法如下;
int find(int x)
{
<span style="white-space:pre">	</span>if(x == per[x]) return x;
return per[x] = find(per[x]);
}

void hebing(int x,int y)
{
int fx = find(x);
int fy = find(y);
if(fx != fy)
{
per[fx] = fy;
}
}

int main()
{
while(scanf("%d%d",&n,&m)!=EOF)//忘记了加EOF
{
for(int t = 0; t < m; t++)
scanf("%d%d%d",&c[t].s,&c[t].e,&c[t].w);
g();//最近大脑老短路,总是忘记这一句 找到BUG了 对per数组赋值必须从0开始赋值
sort(c,c+m,cmp);
int flag = 0; int s = 0;
for(int i = 0; i < m; i++)
{
if(find(c[i].s) != find(c[i].e))
{
hebing(c[i].s,c[i].e);
s = s + c[i].w;
}
}
flag = 0;
for(int i = 0; i < n; i++)
{
if(i == per[i])
{
flag++;
if(flag>1)
break;
}
}
if(flag > 1) printf("impossible\n\n");
else printf("%d\n\n",s);
}
return 0;
}
水题 找错找了半小时。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: