uva10132File Fragmentation(貪心)

來源:互聯網
上載者:User

標籤:blog   http   檔案   io   2014   for   cti   代碼   

題目:uva10132File Fragmentation


題目大意:有n個檔案,都是相同的,但是不小心打破了,而且每個檔案的裂痕不一樣,每個檔案都損壞成兩個片段。每個檔案的片段都用2進位數表示,然後給出2*n個片段,問這樣的片段能得到的檔案(n個)。如果答案不唯一,給出其中一個就可以。


解題思路:因為每兩個片段形成一個檔案,那麼找出最長的片段,那麼它必然和最小的檔案匹配組成檔案。每種情況都嘗試一下,並且組成檔案後需要驗證一下是否剩餘的片段可以組成這個檔案。


這題的輸入要注意一下,因為它是以空格來隔開兩個輸入的範例。


代碼:

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int N = 300;const int M = 150;int n, sum;char ans[N];int vis[M];struct Fragment {char str[N];int len;}f[M];int cmp (const Fragment & a, const Fragment &b) {return a.len > b.len;}bool judge (int a, int b) {memset(vis, 0, sizeof(vis));vis[a] = vis[b] = 1;char temp[N];for (int i = 0; i < n; i++) {if (vis[i])continue;vis[i] = 1;int j;for (j = i + 1; j < n; j++) {if (vis[j])continue;if (f[i].len + f[j].len == sum) {strcpy (temp, f[i].str);strcat (temp, f[j].str);if (strcmp (temp, ans) == 0) {vis[j] = 1;break;}strcpy (temp, f[j].str);strcat (temp, f[i].str);if (strcmp (temp, ans) == 0) {vis[j] = 1;break;}}}if (j == n)return 0;}return 1;}void solve () {int max = f[0].len;int min;for (int i = 0; i < n; i++)if (f[i].len == sum - max) {min = i;break;}for (int i = 0; i < n; i++) {if (f[i].len != max)return;for (int j = min; j < n; j++) {if (f[j].len != f[min].len)break;strcpy (ans, f[i].str);strcat (ans, f[j].str);if (judge (i, j))return;strcpy (ans, f[j].str);strcat (ans, f[i].str);if (judge (i, j))return;}}}int main () {int t;char ch;scanf ("%d%*c", &t);getchar();while (t--) {n = sum = 0;while (gets(f[n].str) != NULL) {f[n].len = strlen (f[n].str);sum += f[n].len;if (strcmp(f[n].str,"") == 0)break;n++;}sum = sum * 2 / n;//printf ("%d %d\n", sum, n);sort (f, f + n, cmp);/*for (int i = 0; i < n; i++)printf ("%s\n", f[i].str);*/solve();printf ("%s\n", ans);if (t)printf ("\n");}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.