think: 1集合中的元素判斷,判斷兩個元素在經(jīng)過區(qū)間合并之后是否在同一區(qū)間
sdut原題鏈接
電影節(jié) Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 某屆電影節(jié)評選電影,共有兩部電影進入最后評選環(huán)節(jié),有n名觀眾,每個人有一次投票的機會,每個人都按照規(guī)則投給其中一部電影。為了了解情況,記者隨機詢問了一些人,一共詢問了m次,特別神奇的是,記者每次都詢問兩個人,而且這兩個人都把票投給了同一部電影,觀眾編號為1~n。
Input 多組輸入,每組第一行是兩個整數(shù)n,m (2 <= n <=100000,0 <= m < n/2),接下來m行數(shù)據(jù),表示m次詢問,每行數(shù)據(jù)有兩個整數(shù)a,b代表觀眾的編號(1 <= a,b <= n),觀眾a和觀眾b投票給了同一部電影,接下來一行是兩個整數(shù)c,d(1 <= c,d <= n)。
Output 對于每一組輸入,輸出一行,如果觀眾c和觀眾d投票給同一部電影,輸出”same”,如果不能確定,輸出”not sure”。
Example Input 5 2 1 2 2 3 1 3 5 2 1 2 3 4 1 4 5 2 1 2 3 4 2 5
Example Output same not sure not sure
Hint
Author xj
以下為accepted代碼——遞歸
#include <stdio.h>#include <string.h>int f[100004];void init(int n){ for(int i = 1; i <= n; i++) f[i] = i;}int getf(int v){ if(v == f[v]) return v; else { f[v] = getf(f[v]); return f[v]; }}void merge(int u, int v){ int t1 = getf(u); int t2 = getf(v); if(t1 != t2) f[t2] = t1;}int main(){ int n, m, i, u, v, x, y; while(scanf("%d %d", &n, &m) != EOF) { init(n); for(i = 0; i < m; i++) { scanf("%d %d", &u, &v); merge(u, v); } scanf("%d %d", &x, &y); x = getf(x); y = getf(y); if(x == y) printf("same/n"); else printf("not sure/n"); } return 0;}/***************************************************User name: Result: AcceptedTake time: 168msTake Memory: 216KBSubmit time: 2017-02-20 20:39:45****************************************************/以下為accepted代碼——非遞歸
#include <stdio.h>#include <string.h>int f[100004];void init(int n){ for(int i = 1; i <= n; i++) f[i] = i;}int getf(int v){ while(v != f[v]) { v = f[v]; } return v;}void merge(int u, int v){ int t1 = getf(u); int t2 = getf(v); if(t1 != t2) f[t2] = t1;}int main(){ int n, m, i, u, v, x, y; while(scanf("%d %d", &n, &m) != EOF) { init(n); for(i = 0; i < m; i++) { scanf("%d %d", &u, &v); merge(u, v); } scanf("%d %d", &x, &y); x = getf(x); y = getf(y); if(x == y) printf("same/n"); else printf("not sure/n"); } return 0;}/***************************************************User name: Result: AcceptedTake time: 164msTake Memory: 212KBSubmit time: 2017-02-20 20:37:13****************************************************/新聞熱點
疑難解答