Crazy Rows 2009 Round 2 A

2015-05-08

22:45:28

地址:http://code.google.com/codejam/contest/204113/dashboard

题意:给出一个n,然后是n*n的矩阵,题目保证这个矩阵可以转化为下三角矩阵,问最少的操作数,使它成为下三角矩阵。

其实对于矩阵的每一行,我们只需保留它最后一个1所在的列数就好了。

a[i] 为第i行的最右的1所在的列

目的:a[i]要放在的行数应该>=a[i]行&&<=n行

则这样相当于操作一个数组a

从第一行开始找,找到一个可以放在第一行的a[i],(即a[i]<=1),然后把它放在第一行

从第二行开始找,找到一个可以放在第2行的a[i],(即a[i]<=2),然后把它放在第2行

从第3行开始找......

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 const int maxn=44;
 8 
 9 #define LL long long
10 
11 int a[maxn];
12 
13 int main()
14 {
15     freopen("A-small-practice.in","r",stdin);
16     freopen("out.txt","w",stdout);
17 
18     int test;
19 
20     scanf("%d",&test);
21 
22     int cas=1;
23 
24     while(test--)
25     {
26         int n;
27         scanf("%d",&n);
28 
29         for(int i=1;i<=n;i++)
30         {
31             char str[maxn];
32             scanf("%s",&str);
33 
34             int len=strlen(str);
35             for(int j=len-1;j>=0;j--)
36             {
37                 if(str[j]=='1')
38                 {
39                     a[i]=j+1;
40                     break;
41                 }
42                 a[i]=0;
43             }
44         }
45 
46         int ans=0;
47 
48         for(int i=1;i<=n;i++)
49         {
50             int pos=0;
51             for(int j=i;j<=n;j++)
52             {
53                 if(a[j]<=i)
54                 {
55                     pos=j;
56                     break;
57                 }
58             }
59 
60             for(int j=pos;j>i;j--)
61             {
62                 swap(a[j],a[j-1]);
63                 ans++;
64             }
65         }
66 
67         printf("Case #%d: %d
",cas++,ans);
68     }
69 
70     return 0;
71 }
View Code
原文地址:https://www.cnblogs.com/-maybe/p/4489104.html