| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
hope it helpful : )前面的discuss中有前辈已经说过了。只是没说太清楚。
我一开始的思路是令c[i]为cube i下面的cube数目。这样导致的问题是压缩路径时你不知道cube i所在的stack中都有哪些cube,从而无法更新所有位于该stack中的c[i]。若进行穷举更新。则并查集的优势荡然无存。
解决这个问题的办法是令c[i]为cube i到cube p[i]之间的cube数目。另外增设数组total[i]为cube i所在的stack中的cube数。
这样在压缩路径时更新c[i]时只需要令c[i] = c[i] + c[p[i]];若操作过程中有新的合并,则p[i]必发生改变,从而c[p[i]]改变。若没有新的合并,该更新不影响c[i] 的正确性。
表达能力有限,还是贴一段代码吧。呵呵。
int find_set( int x )
{
if ( p[x] == x ) return x;
int temp_px = p[x];
p[x] = find_set( p[x] );
c[x] = c[x] + c[temp_px]; //一定要先更新c[p[i]]再更新c[i]
return p[x];
}
void union_set( int x , int y )
{
int rx = find_set( x );
int ry = find_set( y );
p[ry] = p[rx];
c[ry] = total[rx];
total[rx] += total[ry]; //这里只有total[rx]改变了,位于rx所在
//stack中的其他cube i的total[i]没变
//影响正确性么?NO.最后你需要的只是total[rx]
//其他total[i]用不上
}
p.s. main()中的输出语句是 printf( "%d\n" , total[find_set(x)] - c[x] - 1 );
若你用了压缩路径还TLE,看是不是用了cin ,cout,改为scanf() , printf()
good luck :)
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator