数据分割
小w来到百度之星的赛场上,准备开始实现一个程序自动分析系统。这个程序接受一些形如xi=xj或xi≠xj的相等/不等约束条件作为输入,判定是否可以通过给每个 w 赋适当的值,来满足这些条件。输入包含多组数据。然而粗心的小w不幸地把每组数据之间的分符删掉了。他只知道每组数据都是不可满足的,且若把每组数据的最后一个约束条件去掉,则该组数据是可满足的。请帮助他恢复这些分隔符。Input第1行:一个数字L ,表示后面输入的总行数。之后L 行,每行包含三个整数,i,j,e ,描述一个相等/不等的约束条件,若e=1 ,则该约束条件为xi=xj,若e=0,则该约束条件为xi≠xj。i,j,L≤100000 x i ,x j ≤L
Output
输出共T+1 行。第一行一个整数T ,表示数据组数。接下来T 行的第i 行,一个整数,表示第i组数据中的约束条件个数。
Sample Input
6
2 2 1
2 2 1
1 1 1 3 1 1 1 3 1 1 3 0Sample Output 16
题解:
看了位大佬的解法,感觉很有道理,就照着码了一遍。
原出处:http://blog.csdn.net/jaihk662/article/details/77126423
#include<cstdio> #include<cstring> #include<set> using namespace std; const int N=100010; set<int> cha[N], st; int L, grp, ans[N], sum, rot[N]; int Root( int x ) { while( rot[x]!=-1 ) x=rot[x]; return x; } void Union( int x, int y ) { set<int> :: iterator it; if( x==y ) return; if( cha[x].size()>cha[y].size() ) swap( x, y ); for( it=cha[x].begin(); it!=cha[x].end(); it++ ) { cha[ *it ].erase(x); cha[ *it ].insert(y); cha[y].insert( *it ); } rot[x]=y; } int t1, t2, con; int main() { set<int> :: iterator it; memset( rot, -1, sizeof rot ); for( scanf( "%d", &L ); L; L-- ) { sum++; scanf( "%d%d%d", &t1, &t2, &con ); st.insert( t1 ); t1=Root(t1); st.insert( t2 ); t2=Root(t2); if( con ) { if( t1==t2 || !cha[t1].count(t2) ) Union( t1, t2 ); else { ans[++grp]=sum; sum=0; for( it=st.begin(); it!=st.end(); it++ ) cha[ *it ].clear(), rot[ *it ]=-1; st.clear(); } } else { if( t1==t2 ) { ans[++grp]=sum; sum=0; for( it=st.begin(); it!=st.end(); it++ ) cha[ *it ].clear(), rot[ *it ]=-1; st.clear(); } else cha[t1].insert(t2), cha[t2].insert(t1); } } printf( "%d\n", grp ); for( int i=1; i<=grp; i++) printf( "%d\n", ans[i] ); return 0; }
[HDU6109][2017"百度之星"程序设计大赛 - 初赛(A)]数据分割
最新推荐文章于 2022-11-07 17:06:35 发布