USACO-Contact
来源:http://ace.delos.com/usacoprob2?a=5LTgWx8eTT9&S=contact
这题的想法是,把01串转换成二进制,用hash表存储。
为了区分0和00等类似的情况,将所有的子串的高位加个1,例如:
0就用10来存储,00用100存储。
hash表统计子串个数,然后排序输出就是了。
不过如果用string存储输出的数据,直接输出string,总是会多出一些不可见字符,只能一个一个字符输出了。
/* ID:ay27272 PROG:contact LANG:C++ */ #include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <iostream> using namespace std; char s[300005]; char temp[300000] = {0}; string out[1000]; #define NN 30000 struct data { data(int count, int id): count(count), id(id) {} data() { count = id = 0; } int count, id; friend bool operator < (data a, data b) { return a.count>b.count; } } sum[30000]; string change(int t) { string p; int i; for (i=0; t>0; i++) { p = p + (char)(t%2 + '0'); t /= 2; } p[i-1] = '\0'; return p; } int main() { freopen("contact.in","r",stdin); freopen("contact.out","w",stdout); int A, B, N; scanf("%d%d%d", &A, &B, &N); for (int i=0; i<NN; i++) sum[i] = data(0, i); int num, kk; memset(s, 0, sizeof(s)); int ll=0; while (scanf("%s", temp) != EOF ) { for (int i=0; temp[i]; i++) s[ll++] = temp[i]; memset(temp, 0, sizeof(temp)); } for (int i=0; s[i+A-1]; i++) { kk = 1; num = 0; for (int j=0; s[i+j] && j<A-1; j++) { num += kk*(s[i+j] - '0'); kk *= 2; } for (int j=A-1; s[i+j] && j<B; j++) { num += kk*(s[i+j] - '0'); kk *= 2; sum[num + kk].count++; } } sort(sum, sum+NN); int xx, ii; int i=0, count = 0; while (i<NN && count<N) if (sum[i].count) { count++; printf("%d\n", sum[i].count); xx = sum[i].count; ii = 0; while (sum[i].count == xx) { out[ii] = change(sum[i].id); i++; ii++; } for (int si=0; si<ii; si++) for (int sj=si+1; sj<ii; sj++) if (out[si].length() > out[sj].length() || (out[si].length() == out[sj].length() && out[si] > out[sj])) { string temp = out[si]; out[si] = out[sj]; out[sj] = temp; } for (int si=0; si<ii-1; si++) { for (int sj=0; sj<out[si].length()-1; sj++) printf("%c", out[si][sj]); if (si%6==5) printf("\n"); else printf(" "); } for (int sj=0; sj<out[ii-1].length()-1; sj++) printf("%c", out[ii-1][sj]); printf("\n"); } else i++; return 0; }